简体   繁体   English

合并具有相同键的数组,array_merge_recursive无法正常工作

[英]Merge array with same keys, array_merge_recursive doesn't work as expected

I've two arrays with ids as key and some fields and I would like to merge them but I don't understand why it doesn't work, here is my example code: 我有两个ID为键的数组和一些字段,我想将它们合并,但是我不明白为什么它不起作用,这是我的示例代码:

$Podcasts1 = array("1234" => array('title' => "myTitle", "type" => "myType"));
$Podcast2 = array("1234" => array("content" => "myContent"));
$podcasts = array_merge_recursive($Podcasts1, $Podcast2);
var_dump($Podcasts1, $Podcast2, $podcasts);

There is the result: 结果如下:

array:1 [▼
  1234 => array:2 [▼
    "title" => "myTitle"
    "type" => "myType"
  ]
]
array:1 [▼
  1234 => array:1 [▼
    "content" => "myContent"
  ]
]
array:2 [▼
  0 => array:2 [▼
    "title" => "myTitle"
    "type" => "myType"
  ]
  1 => array:1 [▼
    "content" => "myContent"
  ]
]

And there is the result I woulk like to have: 我想得到的结果是:

array:[
1234 => array(
        "title" => "myTitle"
        "type" => "myType"
        "content" => "myContent")
]

I don't understand why the code given on PHP.net work and mine doesn't 我不明白为什么PHP.net上给出的代码无法正常工作

Code: 码:

$ar1 = array("color" => array("favorite" => "red"), 5);
$ar2 = array(10, "color" => array("favorite" => "green", "blue"));
$result = array_merge_recursive($ar1, $ar2);

Result: 结果:

Array
(
    [color] => Array
        (
            [favorite] => Array
                (
                    [0] => red
                    [1] => green
                )

            [0] => blue
        )

    [0] => 5
    [1] => 10
)

Change the key 1234 to string like 将键1234更改为类似字符串

 $Podcasts1 = array('a' => array('title' => "myTitle", "type" => "myType"));
 $Podcast2 = array('a' => array("content" => "myContent"));
 $podcasts = array_merge_recursive($Podcasts1, $Podcast2);
 var_dump($Podcasts1, $Podcast2, $podcasts);

array_merge_recursive works on string keys. array_merge_recursive适用于字符串键。

It wont work for numeric key as function description says 如功能说明所述,它不适用于数字键

If the input arrays have the same string keys, then the values for these keys are merged together into an array, and this is done recursively, so that if one of the values is an array itself, the function will merge it with a corresponding entry in another array too. 如果输入数组具有相同的字符串键,则这些键的值将合并到一个数组中,然后递归完成,因此,如果值之一是数组本身,则函数会将其与相应的条目合并在另一个数组中。 If, however, the arrays have the same numeric key, the later value will not overwrite the original value, but will be appended. 但是,如果数组具有相同的数字键,则后面的值将不会覆盖原始值,而是将其附加。

Ref Link 参考链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM