解决方案
要从json中的循环中获取总价,我们需要在下面的代码中使用$tot += +$data['price'].",";
$arr = '[{
"id": 1,
"name": "A green door",
"price": 11,
"tags": ["home", "green"]
},
{
"id": 2,
"name": "A green door",
"price": 15,
"tags": ["home", "green"]
},
{
"id": 3,
"name": "A green door",
"price": 10,
"tags": ["home", "green"]
}]';
//print_r($arr);
$arr = json_decode($arr,TRUE);
foreach ($arr as $data)
{
$tot += +$data['price'].",";
}
echo "Total = ".rtrim($tot,',');
答案 0 :(得分:0)
使用此,
$arr = json_decode($arr,TRUE);
echo "Total = ".array_sum(array_column($arr,"price"));
array_sum - 计算数组中值的总和
array_column - 返回输入数组中单个列的值
试一试,这样可行。
答案 1 :(得分:0)
$ arr = json_decode($ arr,TRUE);
foreach ($arr as $data)
{
$tot[] =$data['price'];
}
echo "Total=".array_sum($tot);