[英]Create an associative array in jquery using php array
I need to create an assosiative array in jQuery from PHP. 我需要从PHP在jQuery中创建关联数组。
Here is my script so far. 到目前为止,这是我的脚本。
selectedStoresDict
is json
encoded array with values ["Lahore", "Islamabad"]
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!");
However my console is showing that its not an array. 但是我的控制台显示它不是数组。 I want something like this:
我想要这样的东西:
[{ id: 1, text: 'Lahore' }, { id: 2, text: 'Islamabad' }]
I think this should be a JS question instead of a PHP one, but here you have. 我认为这应该是一个JS问题,而不是PHP问题,但是您有。 You were almost there:
您几乎在那里:
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!");
An array in JS is represented with [], so you need to initialize it like that, then just push the info (in this case, and object with keys and values). JS中的数组用[]表示,因此您需要像这样初始化它,然后仅推送信息(在这种情况下,以及带有键和值的对象)。 Also for ids starting with 1, you must initialize i = 1.
同样对于以1开头的ID,您还必须初始化i = 1。
No need to loop thru. 无需循环。
Just json_encode the array 只是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.