I want to change a value in a multidimensional array if the corresponding key is found in another flat associative array.
I have these two arrays:
$full = [ 'Cars' => [ 'Volvo' => 0, 'Mercedes' => 0, 'BMW' => 0, 'Audi' => 0 ], 'Motorcycle' => [ 'Ducati' => 0, 'Honda' => 0, 'Suzuki' => 0, 'KTM' => 0 ] ]; $semi = [ 'Volvo' => 1, 'Audi' => 1 ];
I want the array to look like this:
Array ( [Cars] => Array ( [Volvo] => 1 [Mercedes] => 0 [BMW] => 0 [Audi] => 1 ) [Motorcycle] => Array ( [Ducati] => 0 [Honda] => 0 [Suzuki] => 0 [KTM] => 0 ) )
I get the $semi array from the input field and want to merge it into $full to save it to my database.
I have tried array_replace()
like:
$replaced = array_replace($full, $semi);
You only need to access "leafnodes" and iterate and modify the entire array very directly using
array_walk_recursive()
.Modern "arrow function" syntax allows access to half arrays without having to write
use()
.This method will never make iterative function calls. It modifies
$v
by reference (&$v
), using the "additive assignment" combining operator (=
) and the null combining operator (? ?
) Conditionally increment the value in the full array found in half the array.Code: (Demo)
Not using
array_walk_recursive()
will require using nested loops to add qualified manufacturers.Code: (Demo)
You should loop over the
$semi
array and check if it exists in one of the$full
arrays and then add to it: