将Convert multidimensional array values into a one-dimensional array
P粉969666670
P粉969666670 2024-02-03 23:06:59
0
2
332

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粉969666670
P粉969666670

reply all(2)
P粉738248522

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粉151720173

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;
        }
    }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!