我需要粘合几个包含n
关联数组的索引数组(下面的示例)。我不关心外部数组的索引,我只关心内部数组的键。我已经尝试了几种方法,并且(令人惊讶的是)其中只有一种 - 最丑陋的 - 确实有效。所以我开始怀疑我是否缺少一些聪明/快速的东西。
PHP 版本:5.3+(如果重要的话)
这就是我所拥有的:
$arrayA = array(
array(
'foo' => 1,
'bar' => 2,
'baz' => 3
),
array(
'foo' => 12,
'bar' => 22,
'baz' => 32
),
);
$arrayB = array(
array(
'foo' => 21,
'bar' => 22,
'baz' => 23
),
array(
'foo' => 212,
'bar' => 222,
'baz' => 232
),
);
这就是我想要的:
$arrayC = array(
array(
'foo' => 1,
'bar' => 2,
'baz' => 3
),
array(
'foo' => 12,
'bar' => 22,
'baz' => 32
),
array(
'foo' => 21,
'bar' => 22,
'baz' => 23
),
array(
'foo' => 212,
'bar' => 222,
'baz' => 232
),
);
这是我尝试过的:
$arrayD = $arrayA;
foreach($arrayB as $value)
{
$arrayD[] = $value;
}
$arrayE = array_push($arrayA, $arrayB);
$arrayF = $arrayA + $arrayB;
$arrayG = array_merge($arrayA, $arrayB);
print_r($arrayC == $arrayD); //TRUE - it works
print_r($arrayC == $arrayE); //FALSE
print_r($arrayC == $arrayF); //FALSE
print_r($arrayC == $arrayG); //FALSE
为什么我认为这array_merge($arrayA, $arrayB)
不起作用:
$arrayD = $arrayA;
foreach($arrayB as $value)
{
$arrayD[] = $value;
}
$arrayE = array_push($arrayA, $arrayB); // <-- after this line $arrayA is already broken
$arrayF = $arrayA + $arrayB;
$arrayG = array_merge($arrayA, $arrayB); // because $arrayA was broken I thought it didn't work
有没有比 foreach() 方法更简单/更快/更聪明的方法?