我试图找到以下问题的简单答案,但失败了。
我有一个 2D 数组和一个 1D 数组:
$arr_2D = array(
array("product" => "apple", "quantity" => 2),
array("product" => "Orange", "quantity" => 4),
array("product" => "Banana", "quantity" => 5),
array("product" => "Mango", "quantity" => 7)
);
$element = array("product" => "Lemon", "quantity" => 9);
我希望将一维数组推入二维数组,并得到一个新的大二维数组:
$arr_2D = array(
array("product" => "apple", "quantity" => 2),
array("product" => "Orange", "quantity" => 4),
array("product" => "Banana", "quantity" => 5),
array("product" => "Mango", "quantity" => 7),
array("product" => "Lemon", "quantity" => 9)
);
我尝试过:
$arr_2D = array_push($arr_2D, $element);
但它不起作用;它返回
5
。
如何使用
array_push()
?
这是你想要的吗?
array_push()
和简写 []
表示法都会将 $element
数组添加到 $arr_2D
数组的末尾 :
$arr_2D = array(
array("product" => "apple", "quantity" => 2),
array("product" => "Orange", "quantity" => 4),
array("product" => "Banana", "quantity" => 5),
array("product" => "Mango", "quantity" => 7)
);
$element = array("product" => "Lemon", "quantity" => 9);
//using array_push()
array_push($arr_2D, $element);
//using shorthand notation
$arr_2D[] = $element;
//printing the updated 2D array
print_r($arr_2D);
输出:
Array
(
[0] => Array
(
[product] => apple
[quantity] => 2
)
[1] => Array
(
[product] => Orange
[quantity] => 4
)
[2] => Array
(
[product] => Banana
[quantity] => 5
)
[3] => Array
(
[product] => Mango
[quantity] => 7
)
[4] => Array
(
[product] => Lemon
[quantity] => 9
)
)