Skip to content
Advertisement

Replace multidimensional array values with one-dimensional array

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:

$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 back from my input field and want to merge it into $full to save it into my database.

I already tried array_replace() like:

$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:

foreach ($semi as $semiItem => $semiValue) {
    foreach ($full as &$fullItems) {
        if (isset($fullItems[$semiItem])) {
            $fullItems[$semiItem] = $semiValue;
        }
    }
}

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement