Sunny raturi Sunny raturi - 5 months ago 9
JSON Question

How to Add the particular key values in JSON

[marketing] => [{"quartername":"Q2","tactic":"Single Email Campaign","level1":"8000","level2":"6000","level3":"5000","level4":"3000","level5":"1500","level6":"1000","level7":"800","level8":"600","level9":"500","level10":"65"},{"quartername":"Q2","tactic":"Multi-Touch Email Campaign","level1":"350","level2":"200","level3":"156","level4":"142","level5":"122","level6":"112","level7":"80","level8":"65","level9":"35","level10":"15"}]


i have a json data.when i decode the json the value accure:

Array
(
[0] => stdClass Object
(
[quartername] => Q2
[tactic] => Single Email Campaign
[level1] => 8000
[level2] => 6000
[level3] => 5000
[level4] => 3000
[level5] => 1500
[level6] => 1000
[level7] => 800
[level8] => 600
[level9] => 500
[level10] => 65
)

[1] => stdClass Object
(
[quartername] => Q2
[tactic] => Multi-Touch Email Campaign
[level1] => 350
[level2] => 200
[level3] => 156
[level4] => 142
[level5] => 122
[level6] => 112
[level7] => 80
[level8] => 65
[level9] => 35
[level10] => 15
)

)


i just want that they compare the 'quartername' and then add the value of index 0 key level 1 value to index level 2 level 1 value.

The array i want to create is similar as:

Array
(
[0] => stdClass Object
(
[quartername] => Q2
[tactic] =>
[level1] => 8350
[level2] => 6200
[level3] => 5156
[level4] => 3142
[level5] => 1622
[level6] => 1112
[level7] => 880
[level8] => 665
[level9] => 535
[level10] => 80
)


here the code i tried :

$a=json_decode($obj_total[$i]['marketing']);


foreach($a as $key=>$val)
{
foreach($val as $datakey=> $data)
{
$dte[]=$val->$datakey;

}
}
echo "<pre>"; print_r(array_sum($dte));echo "</pre>";
}

Answer
try this code:

     for($i=0;$i<count($obj_total);$i++)
            {

            $a=json_decode($obj_total[$i]['marketing']);

        $sumArray = array();

            foreach ($a as $k=>$subArray) {
              foreach ($subArray as $id=>$value) {
                $sumArray[$id]+=$value;
              }
            }

echo "<pre>"; print_r($sumArray);echo "</pre>";
             }
Comments