我有两个带有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
)
答案 0 :(得分:0)
将键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适用于字符串键。
答案 1 :(得分:0)
它不适用于数字键,因为功能描述说
如果输入数组具有相同的字符串键,则这些键的值将合并到一个数组中,并且这是递归完成的,因此如果其中一个值是数组本身,则该函数将合并它另一个数组中的相应条目。但是,如果数组具有相同的数字键,则后面的值不会覆盖原始值,但会附加。