在jquery中使用php array创建一个关联数组


Create an associative array in jquery using php array

我需要在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' }]

我认为这应该是一个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>