简体   繁体   中英

Create an associative array in jquery using php array

I need to create an assosiative array in jQuery from PHP.

Here is my script so far. selectedStoresDict is json encoded array with values ["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. 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). Also for ids starting with 1, you must initialize i = 1.

No need to loop thru.

Just json_encode the array

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM