php – Counting the amount by keys?

Question:

Array:

$arr = array(
    'Ford'=> array(
        array('id'=>1,'name'=>'Alex','cost'=>12.50),
        array('id'=>2,'name'=>'Max','cost'=>55.11),
        array('id'=>3,'name'=>'Igor','cost'=>18.00)
    ),
    'BMW'=> array(
        array('id'=>1,'name'=>'Dmitry','cost'=>16.30),
        array('id'=>2,'name'=>'Vlad','cost'=>15.55),
        array('id'=>3,'name'=>'Stas','cost'=>8.00)
    ),
);

How to calculate the amount for each car and add a key with its value to each car? Well that is add up all cost , ex.

['BMW']['Price'] = (16.30 + 15.55 + 8.00) = 39,85

@xEdelweiss , this is what came out:

   foreach ($arr as $key=>$val) {
        $sum = 0;
        foreach ($val as $m) {
            $sum+=$m['cost'];
        }
        $arr[$key]['Price'] = $sum;
    }

We can say Решение найдено .

By request

foreach ($arr as $key=>$val) {
    $arr[$key]['Price'] = 0;
    foreach ($val as $m)
        $arr[$key]['Price'] += $m['cost'];
}

Answer:

Pretty:

$sum = array();

foreach ($arr as $carType => $car) {
    $sum[$carType] = array_sum(array_map(function ($row) {
        return $row['cost'];
    }, $car));
}

var_dump($sum);

array(2) { ["Ford"]=> float(85.61) ["BMW"]=> float(39.85) }

Scroll to Top
AllEscort