<?php
$json = '[{"clientName":"Audi","model":"A6","cost":40000},{"clientName":"Audi","model":"S8","cost":90000},{"clientName":"VW","model":"GolfV","cost":5000},{"clientName":"VW","model":"GolfV","cost":3500},{"clientName":"Audi","model":"RS6","cost":120000},{"clientName":"VW","model":"PassatCC","cost":35000}]';
$array = json_decode($json, true);
$totals = [];
$makes = [];
$modelTotals = [];
foreach ($array as $row) {
// Set defaults to suppress notices
$totals[$row['clientName']] = isset($totals[$row['clientName']]) ? $totals[$row['clientName']] : 0;
$modelTotals[$row['model']] = isset($modelTotals[$row['model']]) ? $modelTotals[$row['model']] : 0;
$totals[$row['clientName']] += $row['cost'];
$makes[$row['clientName']][$row['model']] = $row;
$modelTotals[$row['model']] += $row['cost'];
}
foreach($makes as $client => $cars) {
echo $client.' total: '.$totals[$client]."\n";
foreach($cars as $model) {
echo $model['model'].' '.$modelTotals[$model['model']]."\n";
}
}
preferences:
26.58 ms | 404 KiB | 5 Q