如何在多个json数组中求和。 我的表格中每个金额都添加到json数组中,我想根据ID将json数组中的所有金额相加,请帮助
| id | particulars | client_id
| 140 | [{"amt":"850","ptr":"ITR FEE"}] | 1872
| 1637 | [{"amt":"900","ptr":"ITR RET 2018-19"}] | 1872
我的查询是这样的:
$fetchfbillamt = $ketObj->runquery("SELECT", "*", "vksoft_fbill", array(), "where client_id=".'1872'."");
if (isset($fetchfbillamt) && is_array($fetchfbillamt) &&
count($fetchfbillamt) > 0)
{
$fbillencodeamt = $fetchfbillamt[0]['particulars'];
$fbilldecodeamt = json_decode($fbillencodeamt);
foreach ($fbilldecodeamt as $fbilldecodeamtV)
{
$sumfbillamt +=$fbilldecodeamtV->amt;
}
echo $sumfbillamt;
}
显示输出850
未显示1750
答案 0 :(得分:0)
您在错误的变量上编写了foreach
循环,而应该在$fetchbillamt
上进行迭代。试试这个:
if (isset($fetchfbillamt) && is_array($fetchfbillamt) &&
count($fetchfbillamt) > 0)
{
foreach ($fetchbillamt as $billamt) {
$fbillencodeamt = $billamt['particulars'];
$fbilldecodeamt = json_decode($fbillencodeamt);
$sumfbillamt += $fbilldecodeamt[0]->amt;
}
echo $sumfbillamt;
}
答案 1 :(得分:0)
您将在以下位置犯错, 结果是多维数组,但是您以静态方式分配值。
尝试此代码,
<?php
$fetchfbillamt = array(0=>array('id'=>140,
'particulars'=>'[{"amt":"850","ptr":"ITR FEE"}]'),
1=>array('id'=>1637,
'particulars'=>'[{"amt":"900","ptr":"ITR RET 2018-19"}]'));
$sum = 0;
foreach ($fetchfbillamt as $value){
$sum += json_decode($value['particulars'],true)[0]['amt'];
}
?>
答案 2 :(得分:0)
您似乎只占据了该行的第一行:
$fbillencodeamt = $fetchfbillamt[0]['particulars'];
这实际上应该在您的foreach循环中,如下所示:
$fetchfbillamt = $ketObj->runquery("SELECT", "*", "vksoft_fbill", array(), "where client_id=".'1872'."");
if (isset($fetchfbillamt) && is_array($fetchfbillamt) && count($fetchfbillamt) > 0)
{
foreach ($fetchfbillamt as $fetchedbill)
{
$fbillencodeamt = $fetchedbill['particulars'];
$fbilldecodeamtV = json_decode($fbillencodeamt);
$sumfbillamt += $fbilldecodeamtV['amt'];
}
echo $sumfbillamt;
}
答案 3 :(得分:0)
您可以使用数组精简功能简化代码。我们可以根据需要创建自己的自定义函数并执行操作。
$json = array(['amt' =>"850",'ptr'=>"ITR FEE"], ['amt'=>"900",'ptr'=>"ITR FEE"]);
function sum($carry, $item)
{
$carry += $item['amt'];
return $carry;
}
var_dump(array_reduce($json, "sum"));
会输出int(1750)