[英]Php, array_push, add to existing array
I'm trying to add additional entry to an existing multidimensional array using array_push() 我正在尝试使用array_push()向现有的多维数组添加其他条目
Here is my array: $array = 这是我的数组:$ array =
Array
(
[0] => Array
(
[label] => Black
[quantity] => 10
)
[1] => Array
(
[label] => Yellow
[quantity] => 20
)
[2] => Array
(
[label] => Red
[quantity] => 30
)
)
What I need now is to add price key after each [quantity], so the final result is: 我现在需要的是在每个[数量]之后添加价格键,因此最终结果是:
Array
(
[0] => Array
(
[label] => Black
[quantity] => 10
[price] => 0
)
[1] => Array
(
[label] => Yellow
[quantity] => 20
[price] => 0
)
[2] => Array
(
[label] => Red
[quantity] => 30
[price] => 0
)
)
$price['price'][] = 0;
I have tried using array_push($price['price'], $array)
我已经尝试使用
array_push($price['price'], $array)
but that doesn't work, it just returns number 2. 但这不起作用,它只会返回数字2。
You have an array of arrays. 您有一个数组数组。 You need to iterate over it to add the price to each sub-array.
您需要对其进行迭代以将价格添加到每个子阵列。
foreach($array as $key => $value) {
$array[$key]['price'] = 0;
}
I don't think you want to use array_push()
in this situation. 我不认为您想在这种情况下使用
array_push()
。
foreach ($price as $priceItem) {
$priceItem['price']=0;
$newPrice[]= $priceItem;
}
var_dump($newPrice);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.