2013-10-05 146 views
0

我想改變這個數據,這基本上是從查詢中獲得的。我想將每個部分的數據合併到一個數組中,然後將結果編碼爲json。Php json編碼

Array ([sectionName] => Section C [di] => Robert 2013-10-02 [timeSpent] => 1970,0,1,00,00,06) 
Array ([sectionName] => Section C [di] => John 2013-10-09 [timeSpent] => 1970,0,1,02,13,06) 
Array ([sectionName] => Section D [di] => Tim 2013-10-03 [timeSpent] => 1970,0,1,00,00,17) 

進入

{ 
    "type":"column", 
    "name":"Section C", 
    "color":"Highcharts.getOptions().colors[0]", 
    "data": [{name: Robert 2013-10-02,y:Data.UTC(1970,0,1,00,00,06)},{name: John 2013-10-09,y:Data.UTC(1970,0,1,02,13,06)}] 
    }, 
{"type":"column", 
    "name":"Section C", 
    "color":"Highcharts.getOptions().colors[1]", 
    "data":[{name: Tim 2013-10-03,y:Date.UTC(1970,0,1,00,00,17)}] 
} 

通則

{ 
    type:"column", 
    name: "SectionName", 
    color: "Highcharts.getOptions().colors[1]", 
    data: [{name:di,y:Date.UTC(timeSpent)},{di2 for same section},{di3 etc}] 

我已經試過

$i=0; 
    while($row = db_fetch_array($result)) { 
     //print_r($row); 
     $responce[$i][type]='column'; 
     $responce[$i][name]=$row[sectionName]; 
     $responce[$i][color]='Highcharts.getOptions().colors['.$i.']'; 
     $responce[$i][data]= 
//the problem comes here where i want to combine data depends on sections 
//for each section **di and timeSpent** 
       '['. array(
        name=>$row[di], 
        y=>'Date.UTC('.$row[timeSpent].')' 
       ).']'; 

     $i++; 
    } 
    return json_encode(responce); etc 

這是基達詳細說明。我希望你能理解。

+0

我不認爲有任何可用的JSON庫在PHP中,這將幫助你在這裏。你將不得不像你一樣進步 – Sage

回答

0

假設您的數據按sectionName排序,那麼您可以保留最後一行的名稱的引用,以檢查是否需要創建新的響應行或將數據追加到當前行,以下是該方法的實現:

$i = -1; 
$responce = array(); 
$lastSection = NULL; 
while($row = db_fetch_array($result)) { 
    if($row['sectionName'] != $lastSection){ 
     $lastSection = $row['sectionName']; 
     $i++; 
     $responce[$i]['type'] = 'column'; 
     $responce[$i]['name'] = $row['sectionName']; 
     $responce[$i]['color']='Highcharts.getOptions().colors['.$i.']'; 
    } 
    $responce[$i]['data'][]= (object)array('name'=>$row['di'],'y'=>'Date.UTC('.$row['timeSpent'].')'); 
} 
return json_encode(responce);