phparraysdatepivot

Pivot query results to show dates as columns and ids as rows


I have an array:

Array
(
    [0] => Array
    (
        
        [date] => 2013-01-22
        [id] => 1
        [views] => 33286
          
    )

   [1] => Array
    (
        
        [date] => 2013-01-23
        [id] => 1
        [views] => 33223
          
    )


[2] => Array
    (
        
        [date] => 2013-01-22
        [id] => 2
        [views] => 33223
          
    )

 [3] => Array
    (
        
        [date] => 2013-01-23
        [id] => 2
        [views] => 33223
          
    )
)

As you can see, id 1 & 2 has views in 2 days : 22-01-2013 and 23-01-2013, so my question is how can I print them like this:

id     22-01-2013    23-01-2013
1        33286         33223
2        33223         33223

Solution

  • I doubt your end goal is to write out a table of values. But in case it is, here's some code that would do that.

    <?php
    
    $a = array(
        array('date'=>'2013-01-22', 'id'=>1, 'views'=>33286),
        array('date'=>'2013-01-23', 'id'=>1, 'views'=>33223),
        array('date'=>'2013-01-22', 'id'=>2, 'views'=>33223),
        array('date'=>'2013-01-23', 'id'=>2, 'views'=>33223),
    );
    
    $table = array();
    $cols = array();
    foreach ($a as $item)
    {
       $date = date('d-m-Y', strtotime($item['date']));
       $table[$item['id']][$date] = $item['views'];
       $cols[$date] = 1;
    }
    $cols = array_keys($cols);
    
    header('Content-type: text/plain');
    echo("id\t" . implode("\t", $cols) . "\r");
    foreach ($table as $rowName=>$row)
    {
       echo("$rowName\t");
       foreach ($cols as $colName)
       {
          echo(@$row[$colName] . "\t");
       }
       echo("\r");
    }
    

    P.S. Just so you know, Stack Overflow isn't meant to be a place where we write code for you. I'm just in the mood to write code :-)

    P.P.S. To the real PHP experts here, I'd love to know what optimizations should be made to this code :-)