我尝试在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 ) )
答案 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);