为了账号安全,请及时绑定邮箱和手机立即绑定

从 PHP 创建 JS 数组

从 PHP 创建 JS 数组

PHP
MYYA 2023-04-28 14:24:32
我正在开发 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 数组。任何建议都会很好!编辑:静态代码是一个例子,我想从数据库中获取值,第一个值是国家,第二个值是颜色值。两者都来自数据库。我想反过来使地理图表动态
查看完整描述

3 回答

?
一只甜甜圈

TA贡献1836条经验 获得超5个赞

您正在寻找的函数是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);


查看完整回答
反对 回复 2023-04-28
?
守着星空守着你

TA贡献1799条经验 获得超8个赞

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


<?php


$data = [];

foreach ($something as $statements) {

   $data[] = [$statements["Country"], $statements["Color_Value"]]; 

}

$arrayData = json_encode($data);

?>

arrayData = <?= $arrayData ?>;


查看完整回答
反对 回复 2023-04-28
?
HUH函数

TA贡献1836条经验 获得超4个赞

//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 


//define an blank array 

$chart = [];


//put your axis tags/ texts in on first index

$chart[] = ['Country', 'Colour Count'];


//let's say $reult stores the data fetched from database


foreach ($result as $key => $value){

    //let's assume $value has field with country name as value 

    //and field colour_count have color count values, so

    // $value->country = Country Name

    //$value->colour_count = Color Count Value

    $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];


查看完整回答
反对 回复 2023-04-28
  • 3 回答
  • 0 关注
  • 104 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信