In general, there is an array

$a1 = array('car1' => array('color' => 'black', 'weight'=> '100'), 'car2' => array('color' => 'white', 'weight'=> '200')); 

I do not know how to add a new type 'field' to the ' car1 ' and ' car2 ' arrays with some value, for example, ' car ', ' cargo ', respectively, in the loop.
It turns out only adding to the array $ a1 .
Thank.

    3 answers 3

     foreach($a1 as &$car){ $car['type'] = 'легковая'; } 

    Well, or if there is a separate collection of car categories

     $carTypes = ['car1' => 'легковая', 'car2' => 'грузовая']; foreach($a1 as $name => &$car){ $car['type'] = $carTypes[$name]; } 
    • Only you need to remember to delete the link to $car after the cycle: unset($car); - postrel
    • @postrel, I would not do it - there will be an extra line of cluttering code. The code should be elegant, IMHO. - Goncharov Alexander
    • You can, of course, not litter, but you get this result: 3v4l.org/IMCWM - postrel
     $typeNames = array('car1'=>'легковая', 'car2'=>'грузо foreach(array_keys($a1) as $v) { $a1[$v]['type'] = 'легковая'; } 

      or to all the other answer array_map

       array_map(function($n) { $n['type'] = getType() // функция для вычисления type car },$yourArray);