2016-06-08 70 views
-1
[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:如何添加特定鍵值JSON

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 
     ) 

) 

我只是想,他們比較「quartername」和然後將索引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>"; 
     } 
+2

*「我只是想,他們比較 'quartername',然後將索引0鍵級別1的值添加到索引級別2級別1的值。「*好的。編寫代碼來做到這一點,如果遇到問題,請使用該代碼發佈具體問題,詢問您遇到的具體問題。更多:[*我如何提出一個好問題?](/幫助/如何問)和[*我應該避免問什麼類型的問題?](/ help/dont-ask) –

+0

@RiggsFolly i更新也顯示我想要哪種類型的數組的問題。 –

+0

請參閱@ T.J.Crowder評論。我們期望你應該爲自己做點事情。 ** SO不是免費的編碼服務**,但當您遇到實際編碼問題時,我們非常樂意提供幫助 – RiggsFolly

回答

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