簡體   English   中英

使用php array在jquery中創建一個關聯數組

[英]Create an associative array in jquery using php array

我需要從PHP在jQuery中創建關聯數組。

到目前為止,這是我的腳本。 selectedStoresDictjson編碼的數組,其值為["Lahore", "Islamabad"]

var selectedStores = <?php echo $selectedStoresDict; ?>;
var data = {};
for( i = 0 ; i <= selectedStores.length; i++) {
   data['id'] = i;
   data['text'] = selectedStores[i];
}

console.log(data, "Hello, world!");

但是我的控制台顯示它不是數組。 我想要這樣的東西:

 [{ id: 1, text: 'Lahore' }, { id: 2, text: 'Islamabad' }]

我認為這應該是一個JS問題,而不是PHP問題,但是您有。 您幾乎在那里:

var selectedStores = <?php echo $selectedStoresDict; ?>;
var data = [];
for( i = 1 ; i <= selectedStores.length; i++) {
   data.push({
      id: i,
      text: selectedStores[i]
   });
}

console.log(data, "Hello, world!");

JS中的數組用[]表示,因此您需要像這樣初始化它,然后僅推送信息(在這種情況下,以及帶有鍵和值的對象)。 同樣對於以1開頭的ID,您還必須初始化i = 1。

無需循環。

只是json_encode數組

<?php
$selectedStoresDict[] = array("id"=>1,"text"=>"Lahore");
$selectedStoresDict[] = array("id"=>2,"text"=>"Islamabad");
?>

<script>
console.log('<?php echo json_encode($selectedStoresDict); ?>');
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM