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

时间:2015-09-28 03:56:44

标签: javascript php jquery

我需要在PHP中用jQuery创建一个assosiative数组。

到目前为止,这是我的脚本。 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' }]

2 个答案:

答案 0 :(得分:6)

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

答案 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>
相关问题