带有多维数组的json_encode

时间:2014-02-13 21:13:39

标签: javascript php arrays multidimensional-array json

我一直在关注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);

?>

那个echo给了我一个包含以下结果的数组:

[["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轴。

任何帮助都会非常感激。谢谢!

1 个答案:

答案 0 :(得分:0)

在对JSON进行编码之前,您已使用$year成功地对数组array_multisort()进行了排序。接下来要做的是迭代它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]];