在PHP中使用foreach将元素添加到子数组

时间:2019-03-28 12:56:28

标签: php

我必须将新元素添加到子数组

我使用代码在单个深度数组中设置值,但是现在我必须将值添加到子数组

foreach($result["data"]  as  $val)
{
   $qry = "SELECT count(tin) as tincnt , count(tout) as toutcnt FROM inout 
   WHERE NAME = '".$val["NAME"]."'";
   $prs = oci_parse($conn,$qry);
   $exec = oci_execute($prs);
   oci_define_by_name($prs,"tincnt",$tin);
   oci_define_by_name($prs,"toutcnt",$tout);
   if(!$exec)
   {
        $result['STATUS']="error";
        $result['MESSAGE']="errcd 3 : error fetching data";
   }
   else
   {
         oci_fetch($prs);
         $val->{'TOTAL_IN'} = $tin;
         $val->{'TOTAL_OUT'} = $tout;
   }
}


$val->{'TOTAL_IN'} = $tin; // gives error Attempt to assign property of non-object

输入

{
     "data": [
      {
       "NAME1": "Sukhwinder",
       "PHONE1": "9516152737",
       "ADDRESS": "Jalandhar"
      },
      {
       "NAME1": "Sapna",
       "PHONE1": "8787878787",
       "ADDRESS": "Jalandhar"
      }
    ],
    "STATUS": "SUCCESS",
    "CNT": "2",
    "HASDATA": true
}

所需的输出

{
    "data": [
        {
            "NAME1": "Sukhwinder",
            "PHONE1": "9516152737",
            "ADDRESS": "Jalandhar",
            "TOTAL_IN":5
            "TOTAL_OUT":4
        },
        {

            "NAME1": "Sapna",
            "PHONE1": "8787878787",
            "ADDRESS": "Jalandhar",
            "TOTAL_IN":4
            "TOTAL_OUT":4            
        }
    ],
    "STATUS": "SUCCESS",
    "CNT": "2",
    "HASDATA": true
}

2 个答案:

答案 0 :(得分:1)

为了将值添加到子数组(在您的情况下为$val),您必须通过引用将其传递。试试这个:

foreach($result["data"]  as  &$val)
{
   $qry = "SELECT count(tin) as tincnt , count(tout) as toutcnt FROM inout 
   WHERE NAME = '".$val["NAME"]."'";
   $prs = oci_parse($conn,$qry);
   $exec = oci_execute($prs);
   oci_define_by_name($prs,"tincnt",$tin);
   oci_define_by_name($prs,"toutcnt",$tout);
   if(!$exec)
   {
        $result['STATUS']="error";
        $result['MESSAGE']="errcd 3 : error fetching data";
   }
   else
   {
         oci_fetch($prs);
         $val['TOTAL_IN'] = $tin;
         $val['TOTAL_OUT'] = $tout;
   }
}

答案 1 :(得分:0)

您可以在foreach循环中使用键变量或引用。

键变量

foreach($result["data"] as $key => $val) {
  //[...]
  else {
    oci_fetch($prs);
    $result['data'][$key]['TOTAL_IN'] = $tin;
    $result['data'][$key]['TOTAL_OUT'] = $tout;
  }
}

专业人士:您不必担心在foreach循环后面通过&$val取消引用unset($val);的情况

缺点:比参考语法长得多

参考

foreach($result["data"] as &$val) {
  //[...]
  else {
    oci_fetch($prs);
    $val['TOTAL_IN'] = $tin;
    $val['TOTAL_OUT'] = $tout;
  }
}
// this is important, because $val exists outside of the foreach loop
unset($val);

缺点:您必须担心在foreach循环后通过&$val取消引用unset($val);的设置

Pro:比键变量语法短得多

来源:https://www.php.net/manual/de/control-structures.foreach.php