从 PHP 创建 JS 数组

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


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

  ['China',3],

  ['Russia',2.6],

  ['France',2.5],

  ['Spain',2.4],

  ['Portugal',1.1]

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


for (i in range table.length)


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


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

与获取所有值的 php 表非常相似,我想做同样的事情,但对于 JavaScript 数组。任何建议都会很好!


编辑:静态代码是一个例子,我想从数据库中获取值,第一个值是国家,第二个值是颜色值。两者都来自数据库。我想反过来使地理图表动态


MYYA
浏览 107回答 3
3回答

一只甜甜圈

您正在寻找的函数是json_encode(),但如果您首先构建输入数组,它会更有用。所以像下面这样:// Some code here to generate $arrayData from $statements, giving the following$arrayData = [&nbsp; ['Country' => 'China', 'Color Value' => 3],&nbsp; ['Country' => 'Russia', 'Color Value' => 2.6],&nbsp; ['Country' => 'France', 'Color Value' => 2.5],&nbsp; ['Country' => 'Spain', 'Color Value' => 2.4],&nbsp; ['Country' => 'Portugal', 'Color Value' => 1.1]];// Then, once you have generated $arrayDataecho json_encode($arrayData);

守着星空守着你

您需要先在 php 中准备数组,而不仅仅是 echo json_encode($arr):<?php$data = [];foreach ($something as $statements) {&nbsp; &nbsp;$data[] = [$statements["Country"], $statements["Color_Value"]];&nbsp;}$arrayData = json_encode($data);?>arrayData = <?= $arrayData ?>;

HUH函数

//First you need to check the structure of the result from your database query//Then Loop through the result Object/Array to get the desired structure//Most Common way of doing this is foreach loop&nbsp;//define an blank array&nbsp;$chart = [];//put your axis tags/ texts in on first index$chart[] = ['Country', 'Colour Count'];//let's say $reult stores the data fetched from databaseforeach ($result as $key => $value){&nbsp; &nbsp; //let's assume $value has field with country name as value&nbsp;&nbsp; &nbsp; //and field colour_count have color count values, so&nbsp; &nbsp; // $value->country = Country Name&nbsp; &nbsp; //$value->colour_count = Color Count Value&nbsp; &nbsp; $chart[] = [$value->country, $value->colour_count];}// Once the Loop is finished, you will get an array with your desired format//$chart = [['Country', 'Colour Count'],['France', 12],['USA',34],.....so on];
打开App,查看更多内容
随时随地看视频慕课网APP