3v4l.org

run code in 300+ PHP versions simultaneously
<?php $array = [ ['department' => 'Sale', 'month' => 'February', 'value' => 50], ['department' => 'Sale', 'month' => 'March', 'value' => 35], ['department' => 'Sale', 'month' => 'April', 'value' => 65], ['department' => 'Sale', 'month' => 'May', 'value' => 120], ['department' => 'Dispatch', 'month' => 'February', 'value' => 85], ['department' => 'Dispatch', 'month' => 'March', 'value' => 23], ['department' => 'Dispatch', 'month' => 'April', 'value' => 45], ['department' => 'Dispatch', 'month' => 'May', 'value' => 33], ]; $columns = ['Sale', 'Dispatch', 'Support', 'Calibration']; $columnLookup = array_flip($columns); $result = []; foreach ($array as $row) { $rowKey = $row['month']; $colKey = $columnLookup[$row['department']]; $result[$rowKey][$colKey] = $row['value']; } //var_export($result); foreach ($result as $month => $colVals) { printf( "%' 10s\t%d\t%d\t%d\t%d\n", $month, $colVals[0] ?? 0, $colVals[1] ?? 0, $colVals[2] ?? 0, $colVals[3] ?? 0 ); }
Output for 8.0.1 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.26, 8.4.1 - 8.4.13
February 50 85 0 0 March 35 23 0 0 April 65 45 0 0 May 120 33 0 0

preferences:
91.93 ms | 406 KiB | 5 Q