合并具有相同键的数组,array_merge_recursive 没有按预期工作

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

我有两个以 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);

有结果:

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"
  ]
]

这是我想要的结果:

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

我不明白为什么 PHP.net 上给出的代码可以工作而我的代码却不能

代码:

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

结果:

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

            [0] => blue
        )

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

将密钥 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 适用于字符串键。

如功能描述所述,它不适用于数字键

如果输入数组具有相同的字符串键,则这些键的值将合并到一个数组中,这是递归完成的,因此如果其中一个值是数组本身,函数将合并它也有另一个数组中的相应条目。但是,如果数组具有相同的数字键,则后面的值不会覆盖原始值,而是会被追加。

Ref Link