Home > Enterprise >  Replace multidimensional array values with one-dimensional array
Replace multidimensional array values with one-dimensional array

Time:07-02

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);

CodePudding user response:

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;
        }
    }
}

CodePudding user response:

You only need to visit "leafnodes", it will be very direct to iterate and modify the full array with array_walk_recursive().

Modern "arrow function" syntax allows access to the semi array without writing use().

This approach makes absolutely no iterated function calls. It modifies $v by reference (&$v), uses the "addition assignment" combined operator ( =), and the null coalescing opetator (??) to conditionally increase values in the full array which are found in the semi array.

Code: (Demo)

array_walk_recursive(
    $full,
    fn(&$v, $k) => $v  = $semi[$k] ?? 0
);

var_export($full);

Not using array_walk_recursive() would necessitate using nested loops to increase qualifying manufacturers.

Code: (Demo)

foreach ($full as &$manufacturers) {
    foreach ($manufacturers as $m => &$count) {
        $count  = $semi[$m] ?? 0;
    }
}
var_export($full);
  • Related