我有json对象,我想在其中添加'quantity'字段。我的代码是here
while($row=mysql_fetch_array($result)){
$posts = json_decode($row['value'],true);
array_push($response,$posts);
}
//print_r($response);
foreach($response as $value){
//$plus +=1;
$plus = $plus+$value['quantity'];
}
print_r($response)
然后给出:
Array
(
[0] => Array
(
[0] => Array
(
[srno] => 1
[name] => Gaspari Aminolast
[quantity] => 2
[price] => 2920.0000
[total_bill] => 5840
)
[1] => Array
(
[srno] => 2
[name] => Gaspari Amino Max
[quantity] => 2
[price] => 2640.0000
[total_bill] => 5280
)
[2] => Array
(
[srno] => 3
[name] => Myofusion 10Lbs
[quantity] => 2
[price] => 8400.0000
[total_bill] => 16800
)
)
[1] => Array
(
[0] => Array
(
[srno] => 1
[name] => Gaspari Aminolast
[quantity] => 2
[price] => 2920.0000
[total_bill] => 5840
)
[1] => Array
(
[srno] => 2
[name] => Gaspari Amino Max
[quantity] => 2
[price] => 2640.0000
[total_bill] => 5280
)
[2] => Array
(
[srno] => 3
[name] => Myofusion 10Lbs
[quantity] => 2
[price] => 8400.0000
[total_bill] => 16800
)
)
[2] => Array
(
[0] => Array
(
[srno] => 1
[name] => Gaspari Aminolast
[quantity] => 2
[price] => 2920.0000
[total_bill] => 5840
)
[1] => Array
(
[srno] => 2
[name] => Gaspari Amino Max
[quantity] => 2
[price] => 2640.0000
[total_bill] => 5280
)
)
[3] => Array
(
[0] => Array
(
[srno] => 1
[name] => Gaspari Aminolast
[quantity] => 2
[price] => 2920.0000
[total_bill] => 5840
)
[1] => Array
(
[srno] => 2
[name] => Gaspari Amino Max
[quantity] => 2
[price] => 2640.0000
[total_bill] => 5280
)
)
[4] => Array
(
)
[5] => Array
(
)
[6] => Array
(
[0] => Array
(
[srno] => 1
[name] => Gaspari Amino Max
[quantity] => 2
[price] => 2640.0000
[total_bill] => 5280
)
[1] => Array
(
[srno] => 2
[name] => Gaspari Aminolast
[quantity] => 2
[price] => 2920.0000
[total_bill] => 5840
)
)
)
答案 0 :(得分:1)
试试这个
plus = 0;
foreach($response as $value){
//$plus +=1;
foreach($value as $val)
{
$plus = $plus+$val['quantity'];
}
}
答案 1 :(得分:1)
我认为问题是你的数组是双嵌套的。您有一个key =>值对的2D数组
foreach($response as $array){
foreach($array as $value){
$plus = $plus+$value['quantity'];
}
}