2012-09-19 65 views
0

數我有這樣創建新陣列,以匹配月

Array 
(
    [interswitch] => Array 
     (
      [0] => Array 
       (
        [month] => 8 
        [transactions] => 5 
       ) 

      [1] => Array 
       (
        [month] => 9 
        [transactions] => 1 
       ) 

     ) 

    [visa] => Array 
     (
      [0] => Array 
       (
        [month] => 8 
        [transactions] => 9 
       ) 

     ) 

) 

由SQL查詢,其查詢表和統計記錄每個月產生的數組的數組。 [月]代表日曆月份。我想用這個數據與HighCharts它接受數據以這種格式

{name: 'Tokyo',data: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1,95.6, 54.4]} 

如何隱蔽在我的陣列更具可讀性數組然後可以通過JSON編碼並轉換爲上述格式 我已經試過這

$_monthly_gateway_usage = array(
       array(
        "name"=>"Interswitch", 
        "data"=>$this->parse_monthly_usage_data($monthly_gateway_usage['interswitch']) 
       ), 
       array(
        "name"=>"Visa", 
        "data"=>$this->parse_monthly_usage_data($monthly_gateway_usage['visa']) 
       ) 

      ); 

private function parse_monthly_usage_data($usage_data = array()) { 

      $months = array("1","2","3","4","5","6","7","8","9","10","11","12"); 
      $_d = array(); 
      foreach ($months as $month) { 
       foreach ($usage_data as $key => $d) { 
        if($d['month'] == $month) 
        { 
         $_d[] = $d['transactions']; 
        } 
        else 
        { 
         $_d[] = 0; 
        } 
       } 
      } 

      return $_d; 
     } 

任何幫助將不勝感激

回答

1

這是一個較短的形式:循環索引是基於幾個月

$_d = array(); 
for($i=1;$i<=12;$i++){ 
    foreach($usage_data as $v){ 
     $_d[$i] += ($v['month']==$i) ? $v['transactions'] : 0; 
    } 
} 
+0

它的工作原理,但其中一個返回的數組長度超過12 – MrFoh

+0

也許這將解決它: $ _d [$ i] + =($ v ['month'] == $ i)? $ v ['transactions']:0; 同月有交易信息嗎?就像那個8月份來過2次?此增加應該在同一個月內添加此交易。 –

+0

第8個月沒有來兩次,查詢計算每個月的所有交易。 – MrFoh