我有以下数组:
Array
(
[0] => Array
(
[id] => 23
[title] => jkl
)
[1] => Array
(
[id] => 478
[title] => lmn
)
[2] => Array
(
[id] => 22
[title] => pqr
)
[3] => Array
(
[id] => 21
[title] => abc
)
)
同样是第二阵列:
Array
(
[0] => Array
(
[id] => 103
[title] => Activities
)
[1] => Array
(
[id] => 76
[title] => Top 10 Ideas
)
[2] => Array
(
[id] => 9
[title] => Best Shopping Areas
)
)
如果第一个数组的计数小于3,我想将第一个数组附加到第二个数组中,所以我使用了数组推送功能,并且这样做:
if (count($secondArr) < 3) {
echo "<pre>";
echo array_push($secondArr, $firstArr);
print_r($result);
exit;
}
现在在array_push之后它显示了这样的数组(多维)
Array
(
[0] => Array
(
[id] => 76
[title] => Activities
)
[1] => Array
(
[id] => 103
[title] => Top 10 Ideas
)
[2] => Array
(
[id] => 9
[title] => Best Shopping Areas
)
[3] => Array
(
[0] => Array
(
[id] => 23
[title] => jkl
)
[1] => Array
(
[id] => 478
[title] => lmn
)
[2] => Array
(
[id] => 22
[title] => pqr
)
[3] => Array
(
[id] => 21
[title] => abc
)
)
)
我不想这样(多维)。我想用键4,5附加等等。如果是,那么可以吗?
感谢。
答案 0 :(得分:2)
您应该使用array_merge
代替。
$result = array_merge($secondArr, $firstArr);
答案 1 :(得分:1)
array_push
将一个新元素插入到数组中。您想合并两个数组:
$firstArray = array_merge($firstArray, $secondArray);
答案 2 :(得分:1)
根据PHP.net specification for array_push:
array_push() treats array as a stack, and pushes the passed variables onto the end of array. The length of array increases by the number of variables pushed. Has the same effect as:
所以它不会起作用。您可能希望以完全相同的方式使用array_merge
而不是array_push
。
答案 3 :(得分:1)
答案 4 :(得分:0)
你可以这样做:
$array1 = array(array(1,2,3),array(1,2,3));
$array2 = array(array(4,5,6),array(4,5,6));
if(count($array2) > 3){
foreach($array2 as $val){
$array1[] = $val;
}
}
print_r($array1);
或者你可以简单地合并:
$new_array = array_merge($array1 , $array2);
答案 5 :(得分:0)
如果您仍然坚持使用数组推送, 试试这个:
if (count($secondArr) < 3) {
echo "<pre>";
foreach($firstArr as $arr){
array_push($secondArr,$arr);
}
print_r($secondArr);
exit;
}
但我同意使用array_merge。
答案 6 :(得分:0)
您可以使用array_merge
尝试以下代码if (count($secondArr) < 3) {
array_merge($secondArr, $firstArr);
}