如何使用PHP基于索引合并两个数组?

时间:2011-08-21 09:18:11

标签: php arrays

如何合并这两个数组:

First Array:

[0] => Array
    (
        [0] => Array
            (
                [id] => 10
            )

        [1] => Array
            (
                [id] => 21
            )

    )

第二阵列:

[1] => Array
    (
        [0] => Array
            (
                [id] => 11
            )

        [1] => Array
            (
                [id] => 22
            )

        [2] => Array
            (
                [id] => 13
            )

    )

我希望结果是:

[0][id]=>10
[1][id]=>11
[2][id]=>21
[3][id]=>22
[4][id]=>13

1 个答案:

答案 0 :(得分:3)

$array1 = array(
    array('id' => 10),
    array('id' => 21),
);
$array2 = array(
    array('id' => 11),
    array('id' => 22),
    array('id' => 13),
);
$new_array = array();

$length = max(count($array1), count($array2));

for ($i = 0; $i < $length; $i++)
{
  if (isset($array1[$i]))
    array_push($new_array, $array1[$i]);
  if (isset($array2[$i]))
    array_push($new_array, $array2[$i]);
}
print_r($new_array);

对我来说这是输出:

Array (
    [0] => Array ( [id] => 10 )
    [1] => Array ( [id] => 11 )
    [2] => Array ( [id] => 21 )
    [3] => Array ( [id] => 22 )
    [4] => Array ( [id] => 13 )
)

编辑:使用max来优化它,就像RiaD所说的那样。 编辑2:忘记在许多i变量前添加$ ...