PHP D3组合用于可视化数据

时间:2017-11-23 12:10:33

标签: javascript php d3.js

我正在尝试可视化来自currencylayer API的数据 我试图以此为例:http://bl.ocks.org/Caged/6476579

这是我的php代码:

<?php
$response = json_decode(file_get_contents("http://apilayer.net/api/live?access_key=xxxxxxxxxxx&format=1", true));

$keys_array = array();
$values_array = array();
$arra = array();
foreach($response->quotes as $key => $value) {
//    echo "$key is at $value\n";
//      array_push($keys_array, substr($key,3));
//    array_push($values_array,$value);

    array_push($arra,{"letter":substr($key,3),"frequency":$value});
}
print_r($arra);
?>

我试图以以下形式实现数据:

[
  {letter: "A", frequency: .08167},
  {letter: "B", frequency: .01492},
  {letter: "C", frequency: .02780},
  {letter: "D", frequency: .04253},
  {letter: "E", frequency: .12702},
  {letter: "F", frequency: .02288},
  {letter: "G", frequency: .02022},
  {letter: "H", frequency: .06094},
  {letter: "I", frequency: .06973},
  {letter: "J", frequency: .00153},
  {letter: "K", frequency: .00747},
  {letter: "L", frequency: .04025},
  {letter: "M", frequency: .02517},
  {letter: "N", frequency: .06749},
  {letter: "O", frequency: .07507},
  {letter: "P", frequency: .01929},
  {letter: "Q", frequency: .00098},
  {letter: "R", frequency: .05987},
  {letter: "S", frequency: .06333},
  {letter: "T", frequency: .09056},
  {letter: "U", frequency: .02758},
  {letter: "V", frequency: .01037},
  {letter: "W", frequency: .02465},
  {letter: "X", frequency: .00150},
  {letter: "Y", frequency: .01971},
  {letter: "Z", frequency: .00074}
]

如果我得到上述格式的值,那么我可以将php变量分配给d3 data变量并相应地进行可视化。

上面的php代码给出了如下错误:

Parse error: syntax error, unexpected '{' in file.php on line 18

请帮助我修复错误并将变量赋值给d3。

2 个答案:

答案 0 :(得分:1)

你错过了使用PHP的JSON,JSON是一个javascript对象的anotation,它在php中不起作用。你需要在php中使用数组,然后将它们编码为json。

<?php
$response = json_decode(file_get_contents("http://apilayer.net/api/live?access_key=xxxxxxxxxxx&format=1", true));

$keys_array = array();
$values_array = array();
$arra = array();
foreach($response->quotes as $key => $value) {
//    echo "$key is at $value\n";
//      array_push($keys_array, substr($key,3));
//    array_push($values_array,$value);

    $arra[] = [
        "letter" => substr($key,3),
        "frequency" => $value
    ];
}
print_r($arra);

// echo json_encode($arra); // to convert the array to json 
?>

答案 1 :(得分:1)

只需更改

中的行
File dir0 = new File("/");
dir0.listFiles();  ----> this works fine and list all files.

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.MOUNT_FORMAT_FILESYSTEMS"/>

由于我没有该文件的内容,因此无法预测它是否可以解决问题。