如何在php中求多个json数组的总和

rdlzhqv9  于 2021-06-18  发布在  Mysql
关注(0)|答案(4)|浏览(308)

如何在多个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

pu3pd22g

pu3pd22g1#

可以使用array reduce函数简化代码。我们可以根据需要创建自己的自定义函数并执行操作。

$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)

des4xlb0

des4xlb02#

你已经写了你的 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;
}
anauzrmj

anauzrmj3#

你会在下面的地方犯错误,结果是多维数组而你是静态赋值的。
试试这个代码,

<?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'];
}

?>
abithluo

abithluo4#

看起来你只是排在第一排: $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;
}

相关问题