Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP array_replace multidimensional array with one-dimensional array

I would like to merge my $semi array into the $full.

I get the $semi array back from my input field and want to merge it into $full to save it into my database.

I have these two arrays:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

array = full
Array
(
    [Cars] => Array
        (
            [Volvo] => 0
            [Mercedes] => 0
            [BMW] => 0
            [Audi] => 0
        )

    [Motorcycle] => Array
        (
            [Ducati] => 0
            [Honda] => 0
            [Suzuki] => 0
            [KTM] => 0
        )
)
array = semi
Array
(
    [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
        )
)

already tried array_replace, array_replace.
tried $replaced = array_replace($full, $semi);

>Solution :

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;
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading