我有两个数组,我需要将它们组合成一个数组。我尝试了array_merge
,array_combine
,但它无效。有人能帮助我吗?
First Array
Array
(
[6] => Array
(
[nid] => 5
[title] => YSL
[field_category] => test
[field_collection_creation] =>
[body] =>
)
)
第二个数组
Array
(
[0] => Array
(
[nid] => 13
[title] => ar
[field_category] => test
[field_collection_creation] =>
[body] =>
)
[1] => Array
(
[nid] => 14
[title] => bi
[field_category] => test
[field_collection_creation] =>
[body] =>
)
[2] => Array
(
[nid] => 28
[title] => lc
[field_category] => test
[field_collection_creation] =>
[body] =>
)
[3] => Array
(
[nid] => 21
[title] => gat
[field_category] => test
[field_collection_creation] =>
[body] =>
)
[4] => Array
(
[nid] => 20
[title] => testle
[field_category] => test
[field_collection_creation] =>
[body] =>
)
[5] => Array
(
[nid] => 29
[title] => test
[field_category] => test
[field_collection_creation] =>
[body] =>
)
)
我如何组合这两个数组,保持它们的键是什么?
答案 0 :(得分:2)
因为 Index不会出现在两个数组中使用通常的foreach
foreach($ar1 as $k=>$v)
$ar2[$k] = $v;
它从一个数组获取键和值,并在其他数组中创建相同的键值对
答案 1 :(得分:1)
只需使用数组union +
运算符合并数组:
// $first and $second - are your arrays respectively
$result = $second + $first; // $result contains the combined array
如果要将第二个数组中的数组元素追加到 第一个数组,而不是覆盖第一个数组中的元素 而不是重新索引,使用 + 数组联合运算符: