从PHP创建JS数组

问题描述 投票:0回答:2

我正在开发Google Geochart,我希望它是动态的。这是使数组存储两个值的静态代码,如下所示。国家/地区是地图的唯一标识符,颜色值就是地图的颜色。 (无关紧要,但上下文)

  arrayData = [['Country','Color Value'],
  ['China',3],
  ['Russia',2.6],
  ['France',2.5],
  ['Spain',2.4],
  ['Portugal',1.1]

我希望能够从取自PHP回波值的for循环中创建此数组。像这样的伪代码;

for (i in range table.length)

 arrayData = [['Country','Color Value'],

 [<?php echo $statements["Country"]; ?>], [<?php echo $statements["Color_Value"]; ?>], 

类似于php表,因为它获取了所有值,但我想对JavaScript数组做同样的事情。任何建议将是仁慈的!

javascript php arrays database google-visualization
2个回答
0
投票

您要查找的函数是json_encode(),但是如果您首先构建输入数组,它将更加有用。

所以如下所示:

// Some code here to generate $arrayData from $statements, giving the following

$arrayData = [
  ['Country' => 'China', 'Color Value' => 3],
  ['Country' => 'Russia', 'Color Value' => 2.6],
  ['Country' => 'France', 'Color Value' => 2.5],
  ['Country' => 'Spain', 'Color Value' => 2.4],
  ['Country' => 'Portugal', 'Color Value' => 1.1]
];


// Then, once you have generated $arrayData

echo json_encode($arrayData);

0
投票

您需要首先在php中准备数组,而不仅仅是回显json_encode($ arr):

<?php

$data = [];
foreach ($something as $statements) {
   $data[] = [$statements["Country"], $statements["Color_Value"]]; 
}
$arrayData = json_encode(data);
?>
arrayData = <?= $arrayData ?>;
© www.soinside.com 2019 - 2024. All rights reserved.