I'm working on trying to turn a basic | seperated file, that looks like this:
10.10.0.139|1623778800.0631|20210615 13:40:00|783||test.php|||end of user login|0.2406407635352
10.10.0.139|1623778800.0631|20210615 13:40:00|783||test.php|||end of user login|0.34064078330994
10.10.0.139|1623778800.0631|20210615 13:40:00|783||test.php||index.php|end of User call|0.50612878799438
into something that looks like this:
[0] => Array
(
[test.php|||end of user login] => 0.2406407635352
)
[1] => Array
(
[test.php|||end of user login] => 0.34064078330994
)
[2] => Array
(
[test.php||index.php|end of User call] => 0.50612878799438
)
so that I can run through the file and get the key, count, min, max and average.
The code that I have so far looks like this:
<?php
$arrayContent = file("test.txt");
$returnArray = array();
$i = 0;
foreach($arrayContent as $row){
// echo $row;
$returnArray[$i++] = explode("|", $row);
}
$contentArray = array();
foreach($returnArray as $row) {
$key = $row[5] . '|' . $row[6] . '|' . $row[7] . '|' . $row[8];
$time = $row[9];
$contentArray[$key] = $time;
}
ksort($contentArray);
?>
when I print_r($contentArray) I'll get this:
Array
(
[soap.php|||end of User call] => 0.50612878799438
[soap.php|||end of user login] => 0.34064078330994
)
It appears to take the last value of end of user login and does not have three lines - 2 for the [soap.php|||end of user login] and 1 for the [soap.php|||end of User call]
My end goal get the output, into a text file to be something like this:
Key Count Min Max Avg
[soap.php|||end of user login], 2, 0.2406407635352, 0.34064078330994, 0.29064077342257
[soap.php|||end of User call], 1, 0.50612878799438, 0.50612878799438, 0.50612878799438
My Answer:
To achieve the desired output with the key, count, min, max, and average values, you can modify your code as follows:
php
$arrayContent = file("test.txt");
$returnArray = array();
$i = 0;
foreach($arrayContent as $row){
$returnArray[$i++] = explode("|", $row);
}
$contentArray = array();
foreach($returnArray as $row) {
$key = $row[5] . '|' . $row[6] . '|' . $row[7] . '|' . $row[8];
$time = $row[9];
if(isset($contentArray[$key])){
$contentArray[$key]['count']++;
$contentArray[$key]['min'] = min($contentArray[$key]['min'], $time);
$contentArray[$key]['max'] = max($contentArray[$key]['max'], $time);
$contentArray[$key]['sum'] += $time;
} else {
$contentArray[$key] = array('count' => 1, 'min' => $time, 'max' => $time, 'sum' => $time);
}
}
ksort($contentArray);
// Output the result
echo "Key\tCount\tMin\tMax\tAvg\n";
foreach($contentArray as $key => $values){
$avg = $values['sum'] / $values['count'];
echo "$key\t{$values['count']}\t{$values['min']}\t{$values['max']}\t$avg\n";
}
?>
This code will calculate the count, min, max, and average values for each unique key in the input file and output the result in the desired format. You can then save this output to a text file using file handling functions in PHP.
Rate this post
4 of 5 based on 3036 votesComments