2015-09-28 93 views
0

我需要在PHP中創建jQuery中的聯合數組。在jQuery中使用php數組創建關聯數組

這是我的腳本到目前爲止。 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' }] 

回答

5

我認爲這應該是一個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.

+0

'ID:I + 1'讓你要找的ID值 –

+0

是我已經爲何+ 1會增加嗎? – guradio

+0

哦,那是真的。我編輯了我的答案。用我的舊版本,你會以0開頭而不是1結尾。 –

0

無需循環。

只是json_encode數組

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

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