etl - Reformat a table with Year Month Day Columns so that each date is a Column Heading in PHP -
suppose have associative array in php tabular data looks following:
kpiname year month day kpicount aead10d-lrz 2014 7 30 29 aead10d-lrz 2014 7 31 40 aead10d-lrz 2014 8 1 49 aead10d-lrz 2014 8 2 34 aead10d-lrz 2014 8 3 32 aead10d-lrz 2014 8 4 30 aead10d-lrz 2014 8 5 30 aead20d-lrz 2014 7 30 25 aead20d-lrz 2014 7 31 31 aead20d-lrz 2014 8 1 47 aead20d-lrz 2014 8 2 17 aead20d-lrz 2014 8 3 12 aead20d-lrz 2014 8 4 37 aead20d-lrz 2014 8 5 30
what performant way reformat following data structure:
kpiname 2014-07-30 2014-07-31 2014-08-01 2014-08-02 2014-08-03 2014-08-04 2014-08-05 aead10d-lrz 29 40 49 34 32 30 30 aead20d-lrz 25 31 47 17 12 37 30
there multiple ways this, here 1 way.
// associative array $data = array( array("kpiname"=>"aead10d-lrz", "year"=>2014, "month"=>7, "day"=>30, "kpicount"=>29), array("kpiname"=>"aead10d-lrz", "year"=>2014, "month"=>7, "day"=>31, "kpicount"=>40), array("kpiname"=>"aead10d-lrz", "year"=>2014, "month"=>8, "day"=>1, "kpicount"=>49), array("kpiname"=>"aead10d-lrz", "year"=>2014, "month"=>8, "day"=>2, "kpicount"=>34), array("kpiname"=>"aead10d-lrz", "year"=>2014, "month"=>8, "day"=>3, "kpicount"=>32), array("kpiname"=>"aead10d-lrz", "year"=>2014, "month"=>8, "day"=>4, "kpicount"=>30), array("kpiname"=>"aead10d-lrz", "year"=>2014, "month"=>8, "day"=>5, "kpicount"=>30), array("kpiname"=>"aead20d-lrz", "year"=>2014, "month"=>7, "day"=>30, "kpicount"=>25), array("kpiname"=>"aead20d-lrz", "year"=>2014, "month"=>7, "day"=>31, "kpicount"=>31), array("kpiname"=>"aead20d-lrz", "year"=>2014, "month"=>8, "day"=>1, "kpicount"=>47), array("kpiname"=>"aead20d-lrz", "year"=>2014, "month"=>8, "day"=>2, "kpicount"=>17), array("kpiname"=>"aead20d-lrz", "year"=>2014, "month"=>8, "day"=>3, "kpicount"=>12), array("kpiname"=>"aead20d-lrz", "year"=>2014, "month"=>8, "day"=>4, "kpicount"=>37), array("kpiname"=>"aead20d-lrz", "year"=>2014, "month"=>8, "day"=>5, "kpicount"=>30), ); // array hold reordered array $newdata = array(); // reorder array $newdata, grouped kpiname data key foreach($data $row){ $newdata[$row["kpiname"]][$row["year"]."-".$row["month"]."-".$row["day"]]=$row["kpicount"]; } // date keys use headers $headers = array_keys(reset($newdata)); // build table echo "<table><tr>"; echo "<td>kpiname</td>"; // loop through date headers foreach($headers $header){ echo "<td>{$header}</td>"; } echo "</tr>"; // loop through each kpiname row foreach($newdata $key=>$row){ echo "<tr>"; echo "<td>{$key}</td>"; // loop through each date value foreach($row $data){ echo "<td>{$data}</td>"; } echo "</tr>"; } echo "</table>";
Comments
Post a Comment