合并两个数组结果错误的数组,其中包含第二个数组作为数组而不是两者的完整

时间:2018-02-01 11:30:07

标签: php

我尝试在php中使用array_merge,但结果数组不正确

1. Array ( [id] => 12 [name] => Popular ) 
2. Array ( [0] => Array ( [id] => 8 [name] => Flowers ) [1] => Array ( [id] => 10 [name] => Chocolates ) [2] => Array ( [id] => 11 [name] => Sweets and Dry Fruits ) ) 

结果数组

Array ( [id] => 12 [name] => Popular [0] => Array ( [id] => 8 [name] => Flowers ) [1] => Array ( [id] => 10 [name] => Chocolates ) [2] => Array ( [id] => 11 [name] => Sweets and Dry Fruits ) )

1 个答案:

答案 0 :(得分:0)

如果您只想以与现有数据相同的格式添加新数据,请使用[]而不是array_merge()

$array1 = array( 'id' => 12, 'name' => 'Popular');
$array2 = array(array( 'id' => 8, 'name' => 'Flowers'),
    array( 'id' => 10, 'name' => 'Chocolates'),
    array( 'id' => 11, 'name' => 'Sweets and Dry Fruits')
);

$array2[] = $array1;
print_r($array2);

...输出

Array
(
    [0] => Array
        (
            [id] => 8
            [name] => Flowers
        )

    [1] => Array
        (
            [id] => 10
            [name] => Chocolates
        )

    [2] => Array
        (
            [id] => 11
            [name] => Sweets and Dry Fruits
        )

    [3] => Array
        (
            [id] => 12
            [name] => Popular
        )

)

如果您希望数据位于前面,那么您需要创建该数据的数组,然后使用array_merge() ...

$array3 = array_merge(array($array1), $array2);
print_r( $array3);