如果键是数组,PHP合并到相同的数组

时间:2015-03-03 06:14:25

标签: php arrays

我有一个如下所示的多数组,如果一个键(其他)是一个数组,则需要合并。我尝试使用array_merge(call_user_func_array('array_merge',$ myArr))并且它没有按预期工作。

Array
(
    [12] => Australia
    [36] => Canada
    [82] => Germany
    [97] => Hong Kong
    [100] => India
    [154] => New Zealand
    [190] => Singapore
    [222] => United Arab Emirates
    [223] => United Kingdom
    [224] => United States of America
    [Others] => Array
        (
            [1] => Afghanistan
            [3] => Algeria
            [4] => Andorra
            [6] => Anguilla
         )
)

我如何转换就像下面一样,没有丢失钥匙。

Array
(
    [12] => Australia
    [36] => Canada
    [82] => Germany
    [97] => Hong Kong
    [100] => India
    [154] => New Zealand
    [190] => Singapore
    [222] => United Arab Emirates
    [223] => United Kingdom
    [224] => United States of America
    [1] => Afghanistan
    [3] => Algeria
    [4] => Andorra
    [6] => Anguilla
)

更新 我可以这样做,但我不确定是这样做的。

$temp = $myArr['others'];
unset($myArr['others']);
array_replace($myArr , $temp);

3 个答案:

答案 0 :(得分:0)

为什么不做这样的事情:

if (array_key_exists('Others', $countries)) {
    foreach ($countries['Others'] as $index => $otherCountry) {
        if (array_key_exists($index, $countries)) {
            // handle collisions
        } else {
            $countries[$index] = $otherCountry;
        }
    }
}

虽然这是不好的做法,但这里有一个衬垫可以压扁你的阵列:

$allCountries = iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($countries)));

答案 1 :(得分:0)

我已经制作了一个可能适合您的自定义功能。它可以处理那里有许多嵌套数组。

<?php
$test = array(
    12 => 'Australia',
    36 => 'Canada',
    82 => 'Germany',
    97 => 'Hong Kong',
    100 => 'India',
    154 => 'New Zealand',
    190 => 'Singapore',
    222 => 'United Arab Emirates',
    223 => 'United Kingdom',
    224 => 'United States of America',
    'Others' => array(
        1 => 'Afghanistan',
        3 => 'Algeria',
        4 => 'Andorra',
        6 => 'Anguilla',
        "test" => array(10 => 'Hello', 11 => 'World')
    )
);

$new = array();
my_merge($new, $test);
var_dump($new);

function my_merge(&$result, $source)
{
    foreach ($source as $key => $value) {
        if (is_array($value)) {
            my_merge($result, $value);
        } else {
            $result[$key] = $value;
        }
    }
}

答案 2 :(得分:0)

您可以使用迭代器展平数组:

$myArr = iterator_to_array(new RecursiveIteratorIterator(
  new RecursiveArrayIterator($myArr)
));