<?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";
}
}
- Output for 5.6.0 - 5.6.40, 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.34, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 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
- Audi total: 250000
A6 40000
S8 90000
RS6 120000
VW total: 43500
GolfV 8500
PassatCC 35000
preferences:
139.11 ms | 408 KiB | 5 Q