亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從 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 關注
  • 171 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號