1

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' }]
0

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

you need id: i + 1 to get the id values you're looking for
Oh, that's true. I edited my answer. With my old wnaser you would end with ids starting with 0 instead of 1.
0

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.