2013-02-12 98 views
2

我想要得到最好的做法來處理我的陣得到的格式與此類似一個JSON(最好使用圖表工作)數組用PHP的JSON輸出

{ 
    "serieMonth":["Aug-12","Sep-12","Oct-12","Nov-12","Dec-12","Jan-13","Feb-13"], 
    "serieCA":[4214,10119,13325,12818,7177,20628,7664], 
    "serieAdwordsCA":[0,0,0,0,0,310,332], 
    "serieBooking":[10,28,46,34,17,51,16], 
    "serieAdwords":[0,0,0,0,0,1,1], 
    "serieTotalBooking":[10,28,46,34,17,52,17], 
    "serieCartRepartition":[421,361,290,377,422,397,451], 
    "serieTotalCart":[421,361,290,377,422,397,451] 
    } 

其實我的輸出看起來是這樣的:

[ 
{"date_year":"2012","date_month":"08","ad_cost":"0.0","ad_clicks":"0"}, 
{"date_year":"2012","date_month":"09","ad_cost":"0.0","ad_clicks":"0"}, 
{"date_year":"2012","date_month":"10","ad_cost":"0.0","ad_clicks":"0"}, 
{"date_year":"2012","date_month":"11","ad_cost":"0.0","ad_clicks":"0"}, 
{"date_year":"2012","date_month":"12","ad_cost":"44.9","ad_clicks":"43"}, 
{"date_year":"2013","date_month":"01","ad_cost":"297.56","ad_clicks":"462"}, 
{"date_year":"2013","date_month":"02","ad_cost":"82.5","ad_clicks":"103"} 
] 

而且我使用JavaScript來改變它:

var xAxisLabels = new Array(), 
adClicks = new Array(), 
adCost = new Array(); 
$.each(data, function(i,v) { 
    xAxisLabels.push(v["date_month"]+'/'+v["date_year"]); 
    adCost.push(parseInt(v["ad_cost"])); 
    adClicks.push(parseInt(v["ad_clicks"])); 
}); 

我在找做我的最好辦法t在PHP中,因爲我通過google api得到這些數據,這裏是我的php。

// dimensions 
$dimensions = 'ga:year,ga:month'; 
$_params[] = 'date_year'; 
$_params[] = 'date_month'; 
// metrics 
$metrics = 'ga:adCost,ga:adClicks'; 
$_params[] = 'ad_cost'; 
$_params[] = 'ad_clicks'; 

$response = $service->data_ga->get('ga:' . $projectId, $from, $to, $metrics, array('dimensions' => $dimensions)); 

$analyticsStats = array(); 
foreach ($response['rows'] as $row) { 
    $dataRow = array(); 
    foreach ($_params as $colNr => $column) { 
    $dataRow[$column] = $row[$colNr]; 
    } 
    array_push($analyticsStats, $dataRow); 
} 
+0

「輸出」似乎並沒有包含打造的「輸入」所需的所有值。 – 2013-02-12 12:07:47

+0

是的輸出是我想要的格式的例子。 – Shipow 2013-02-12 12:13:32

回答

3

您可以構建陣列再加入項目在一個循環中的子數組的數組:

$output = array(
    "serieMonth" => array(), 
    "serieCA" => array(), 
    "serieAdwordsCA" => array(), 
    "serieBooking" => array(), 
    "serieAdwords" => array(), 
    "serieTotalBooking" => array(), 
    "serieCartRepartition" => array(), 
    "serieTotalCart" => array() 
); 
foreach($response["rows"] as $row) { 
    $output["serieMonth"][] = date("Y-M", strtotime("{$row['date_year']}-{$row['date_month']}-01")); 
    $output["serieCA"][] = $row["ad_cost"]; 
    $output["serieAdwordsCA"][] = $row["ad_clicks"]; 
    // etc... 
} 
echo json_encode($output); 
+0

感謝您的幫助 – Shipow 2013-02-12 15:04:24