繁体   English   中英

具有多维数组的json_encode

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM