I would like to change the values in one multidimensional array if a corresponding key is found in another flat, associative array.
I have these two arrays:
JavaScript
x
$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:
JavaScript
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 back from my input field and want to merge it into $full to save it into my database.
I already tried array_replace()
like:
JavaScript
$replaced = array_replace($full, $semi);
Advertisement
Answer
You should loop your $semi
array and check if it exists in one of $full
arrays, then add to it:
JavaScript
foreach ($semi as $semiItem => $semiValue) {
foreach ($full as &$fullItems) {
if (isset($fullItems[$semiItem])) {
$fullItems[$semiItem] = $semiValue;
}
}
}