array_unshift用于多维数组

时间:2013-03-13 23:47:20

标签: php arrays multidimensional-array

我正在尝试将数组作为第一个元素插入到多维数组中。原始数组的示例

Array (
    0 => array ( "point1.0" => "some data", "point2.0" => "some data" )
    1 => array ( "point1.1" => "some data", "point2.1" => "some data" )
)

然后我将要插入的数组作为第一个元素

$newArray = array("point1.2" => "some data", "point2.2" => "some data" )

我的结果应该是

Array (
    0 => array ( "point1.2" => "some data", "point2.2" => "some data" )
    1 => array ( "point1.0" => "some data", "point2.0" => "some data" )
    2 => array ( "point1.1" => "some data", "point2.1" => "some data" )
)
在这种情况下,

array_unshift似乎失败了。有没有比创建新数组和通过foreach循环插入每个子数组更好的解决方案?

1 个答案:

答案 0 :(得分:14)

array_unshift应该适合你。应该注意的是,函数修改传递给它的数组并且不返回新数组,因此你应该将返回值赋给数组变量。

正确:

array_unshift($arr, $newArray);

不正确:

$arr = array_unshift($arr, $newArray);