phparraysmultidimensional-arraygroupingflat-file

Group data from lines of a log file by one column and create subarrays from another column


i have a logfile which is saved as

{time} | {name} | {value1}
{time} | {name} | {value2}
{time} | {name2} | {value3}
{time} | {name3} | {value4}

the {time} is a timestamp in "Seconds since the Unix Epoch"

and the logfile is written line by line so the latest log line is at the bottom,

and I am trying to categorize the values into a php array.

Let's say we have:

{time} | Steve | Pizza
{time} | Steve | Kebab
{time} | Steve | Burger
{time} | John | Kebab
{time} | John | Ice-Cream
{time} | Dave | Pizza
{time} | Derek | Ice-Cream
{time} | Derek | Fanta

I have exploded into array $lines

this is what I can use to get the variables:

echo $lines[0][1] . "," . $lines[0][2];  // this will print ' Steve,Pizza '
echo $lines[3][2];  // this will print ' Kebab '

I am trying to somehow code an array using ' $lines[$x][1] ' as the array keys and ' $lines[$x][2] ' as the array values so I can call:

print_r($new_array);

to get:

array
     (
  [Steve] => Pizza
          => Kebab
          => Burger
     )
     (
  [John] => Kebab
         => Ice-Cream
     )
     (
  [Dave] => Pizza
     )
     (
  [Derek] => Ice-Cream
          => Fanta
     )

the reason for doing this is I need to display a small table which will look like this:

 _________________________________________
|       Steve       |      Pizza          |
|                   |      Kebab          |
|___________________|_____ Burger ________|
|       John        |      Kebab          |
|___________________|_____ Ice-Cream _____|
|______ Dave _______|_____ Pizza _________|
|       Derek       |      Ice-Cream      |
|___________________|_____ Fanta _________|

the array $lines is already formatted to remove all "log Lines" older than 24 hours....

so I dont think I will need to limit the amount of array keys {names}.


Solution

  • Didn't fully test, but try:

    $new = array();
    foreach($lines as $line)
    {
        $new[$line[1]][] = $line[2];
    }
    print_r($new);
    

    EDIT BY DJ-P.I.M.P...

    $new = array();
    foreach($lines as $line)
    {
    $new[$line[1]][] = $line[2];
    }
    // print_r($new);
    
    
    foreach($new as $key => $news) {
    
    echo $key . "<br>";
    
    foreach($news as $k => $v) {
    
    echo $news[$k] . "<br>";
    
    }
    }
    

    This does exacly as my question was asking .... Kudos, for the initial idea @ Aaron :)