我试图将数组插入到多维数组中作为第一个元素。我的原始数组
的例子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循环插入每个子数组更好的解决方案?
array_unshift
应该适合您。应该注意的是,该函数修改了传递给它的数组,并且不返回一个新数组,因此您应该而不是将返回值赋给数组变量。
正确的:
array_unshift($arr, $newArray);
不正确:
$arr = array_unshift($arr, $newArray);