PHP合并来自普通数组的多维数组键

时间:2014-04-25 09:23:50

标签: php arrays

我有两个我要合并的php数组,一个是多维数组,而针是一个普通的单维数组:

包含所有可能位置的数组:

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

我想将它与后面的multidimentional数组合并:

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

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

我需要最终结果如下:

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

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

为此,我会使用array_merge

<强>代码

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

<强>结果

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

答案 1 :(得分:0)