Search code examples
phparraystabsassociative-array

turning a | seperated file into an associative array in PHP


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

Solution

  • Your code sets the value of the key to last matching time value found in the file, it looks like you want to have an array of values for each key instead. You're also working too hard IMO, let fgetcsv do the work for you.

    <?php
    
    $handle = fopen('test.csv', 'r');
    
    $contentArray = [];
    while (($row = fgetcsv($handle, 0, '|')) !== false)
    {
        $key = $row[5] . '|' . $row[6] . '|' . $row[7] . '|' . $row[8];
    
        if(!array_key_exists($key, $contentArray))
        {
            $contentArray[$key] = [];
        }
    
        $time = $row[9];
        $contentArray[$key][] = $time;
    }
    
    fclose($handle);
    
    ksort($contentArray);
    
    foreach($contentArray as $key=>$data)
    {
        echo '['.$key.'], '.implode($data, ', ').PHP_EOL;
    }