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);
P粉7382485222024-02-04 20:07:00
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)
array_walk_recursive( $full, fn(&$v, $k) => $v += $semi[$k] ?? 0 ); var_export($full);
Not using array_walk_recursive()
will require using nested loops to add qualified manufacturers.
Code: (Demo)
foreach ($full as &$manufacturers) { foreach ($manufacturers as $m => &$count) { $count += $semi[$m] ?? 0; } } var_export($full);
P粉1517201732024-02-04 12:18:10
You should loop over the $semi
array and check if it exists in one of the $full
arrays and then add to it:
foreach ($semi as $semiItem => $semiValue) { foreach ($full as &$fullItems) { if (isset($fullItems[$semiItem])) { $fullItems[$semiItem] = $semiValue; } } }