如何在JSON中添加特定键值

时间:2016-06-08 10:00:41

标签: php arrays json codeigniter

[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"}]

我有一个 json 数据。当我解码json时,值为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
        )

)

我只是希望他们比较'季度名称'然后将索引0键级别1值的值添加到索引级别2级别1值。

我想要创建的数组类似于:

    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
        )

这里是我试过的代码:

    $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>";
        }

1 个答案:

答案 0 :(得分:1)

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>";
             }