如果键是数组,则php合并到同一数组

如果键是数组,则php合并到同一数组,php,arrays,Php,Arrays,我有一个如下所示的多数组,如果一个键(其他键)是数组,则需要合并。我试过使用array\u merge(调用_user\u func\u array('array\u merge',$myArr)),但效果不理想 Array ( [12] => Australia [36] => Canada [82] => Germany [97] => Hong Kong [100] => India [154] => Ne

我有一个如下所示的多数组,如果一个键(其他键)是数组,则需要合并。我试过使用array\u merge(调用_user\u func\u array('array\u 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);

为什么不这样做呢:

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

我已经做了一个自定义函数,可能适合您。它可以处理尽可能多的嵌套数组

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

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

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

向我们展示您的最佳尝试,让我们看看您失败的具体位置。它总是被称为
“others”
,还是可以有其他内部数组?是的,它总是相同的数组。谢谢,但我正在寻找一个单行代码,请查看我上面的更新。我可以问您为什么有这个要求吗?通常不建议隐藏复杂性。我编辑了我的答案,添加了一行有效的语句。但仍不推荐:)