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 ); }

preferences:
14.57 ms | 405 KiB | 5 Q