[英]json_encode with a multidimensional array
我一直在看json_encode
技巧,還沒有弄清楚我要做什么。
我建立了一個php函數,該函數接受一個CSV文件並將數據轉儲到多維數組中(我至少99%確信這是正確的)。 然后,我需要從數組中獲取數據,並將其放入折線圖中。 這是我的PHP代碼,用於從CSV檢索數據(並在最后添加一個值,該值是對數組中其他值中的2個值的計算):
<?php
function readCSV($csvFile) {
$file_handle=fopen($csvFile,'r');
while (!feof($file_handle) ) {
$line_of_text[]=fgetcsv($file_handle,1024);
}
fclose($file_handle);
return $line_of_text;
}
// Set path to CSV file
$csvFile='./example.csv';
$csv=readCSV($csvFile);
array_push($csv[0], "Percentage");
$headers = array_shift($csv);
$i=0;
foreach ($csv as $record) {
$Perc = $record[2] / $record[3];
$Perc = $Perc * 100;
$Perc = round ($Perc, 2);
array_push($csv[$i], $Perc);
$j=0;
$i++;
}
foreach ($csv as $key => $row) {
$year[$key] = $row[0];
}
array_multisort($year, SORT_ASC, $csv);
//print_r($csv);
echo json_encode($csv);
?>
該回聲為我提供了一個具有以下結果的數組:
[["2008","41","412","525","125.2",78.48],["2009","33","393","571","99.9",68.83],["2010","33","450","679","91.9",66.27],["2012","37","400","583","105.8",68.61],["2013","55","450","659","115.1",68.29]]
第一個關鍵是年份。 在我的圖形中,我需要根據x軸上的年份繪制圖表,並且需要繪制鍵1、5和6(均基於年份)。 我還無法弄清楚該怎么做。
圖的格式是這樣的:
var d1 = [[0, 3], [4, 8], [8, 5], [12, 13]];
var d1 = [[2009, 33], [2010, 33], [2012, 37], [2013, 55]];
var d2 = [[2009, 99.9], [2010, 91.9], [2012, 105.8], [2013, 115.1]];
var d3 = [[2009, 68.83], [2010, 66.27], [2012, 68.61], [2013, 68.29]];
其中每組中的第一個值為x軸,第二個值為y軸。
任何幫助將非常感激。 謝謝!
在對JSON進行編碼之前,您已經成功使用array_multisort()
對數組$year
進行了排序。 接下來要做的是將其迭代3次,對於您的三個輸出變量每次迭代一次,並為每個變量生成2D數組。 然后,有了這些之后,就可以使用PHP編寫JavaScript並在各個數組上調用json_encode()
。
// You already sorted $year how you need it
array_multisort($year, SORT_ASC, $csv);
// This will store your final output
$mapped_values = array();
// You want the keys 1,4,5
foreach (array(1,4,5) as $key) {
$temp = array();
// Loop over each year array and make a sub-array of year,key
// 2008, 2008, 2010....
foreach ($csv as $y) {
// intval() & floatval() prevent the output as strings to JSON...
$temp[] = array(intval($y[0]), floatval($y[$key]);
}
// Append the structure to the outer result
// Each of these corresponds to one of the keys 1,4,5...
$mapped_values[] = $temp;
}
// Write it as output:
foreach ($mapped_values as $varnum => $js_var) {
// To get the d1, d2, d3
$num = $varnum + 1;
// Write a var dN = JSON...
// json_encode() will produce the appropriate output
echo "var d{$num} = " . json_encode($js_var) . ";\n";
}
這將產生以下輸出:
var d1 = [[2008,41],[2009,33],[2010,33],[2012,37],[2013,55]];
var d2 = [[2008,125.2],[2009,99.9],[2010,91.9],[2012,105.8],[2013,115.1]];
var d3 = [[2008,78.48],[2009,68.83],[2010,66.27],[2012,68.61],[2013,68.29]];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.