[英]Create an associative array in jquery using php array
我需要从PHP在jQuery中创建关联数组。
到目前为止,这是我的脚本。 selectedStoresDict
是json
编码的数组,其值为["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.