user3572265
user3572265

Reputation: 23

PHP merge multi-dimensional array keys from normal array

I've got these two php arrays I want to merge, one is a multi dimensional array and the needle is a normal single dimensional array :

Array containing ALL possible locations:

Array
(
    [Bedfordview] => 0
    [Killarney] => 0
    [Melrose] => 0
    [Midrand] => 0
    [Morningside] => 0
)

I want to merge it with the follow multidimentional array:

Array
(
    [11] => 
    [12] => Array
        (
            [Bedfordview] => 7
            [Melrose] => 2
            [Midrand] => 87
            [Morningside] => 4
        )

    [13] => Array
        (
            [Morningside] => 8
            [Killarney] => 1
        )
)

I Need the end result to look like this:

Array
(
    [11] => Array
        (
            [Bedfordview] => 0          ==FROM FIRST ARRAY
            [Killarney] => 0            ==FROM FIRST ARRAY
            [Melrose] => 0              ==FROM FIRST ARRAY
            [Midrand] => 0              ==FROM FIRST ARRAY
            [Morningside] => 0          ==FROM FIRST ARRAY
        )
    [12] => Array
        (
            [Bedfordview] => 7
            [Melrose] => 2
            [Midrand] => 87
            [Morningside] => 4
            [Killarney] => 0            ==FROM FIRST ARRAY
        )

    [13] => Array
        (
            [Bedfordview] => 0          ==FROM FIRST ARRAY
            [Melrose] => 0              ==FROM FIRST ARRAY
            [Midrand] => 0              ==FROM FIRST ARRAY
            [Morningside] => 8
            [Killarney] => 1
        )
)

Any ideas?

Upvotes: 2

Views: 56

Answers (2)

jonnu
jonnu

Reputation: 728

For this, I would use array_merge.

Code

<?php

$locations = array(
    'Bedfordview' => 0,
    'Killarney'   => 0,
    'Melrose'     => 0,
    'Midrand'     => 0,
    'Morningside' => 0
);

$data = array(
    11 => array(),
    12 => array(
        'Bedfordview' => 7,
        'Melrose'     => 2,
        'Midrand'     => 87,
        'Morningside' => 4
    ),
    13 => array(
        'Morningside' => 8,
        'Killarney'   => 1
    )
);


$result = array();
foreach ($data as $key => $values) {
    $result[$key] = array_merge($locations, $values);
}

print_r($result);

Result

Array
(
    [11] => Array
        (
            [Bedfordview] => 0
            [Killarney] => 0
            [Melrose] => 0
            [Midrand] => 0
            [Morningside] => 0
        )

    [12] => Array
        (
            [Bedfordview] => 7
            [Killarney] => 0
            [Melrose] => 2
            [Midrand] => 87
            [Morningside] => 4
        )

    [13] => Array
        (
            [Bedfordview] => 0
            [Killarney] => 1
            [Melrose] => 0
            [Midrand] => 0
            [Morningside] => 8
        )
)

Upvotes: 1

Related Questions