1

I'm trying to convert my json object into array. I've saw many questions on SO but that didn't help me.

My PHP Code :

$arr = Array ( [1] => 10 [5] => 20 ) //array key is random

I want to assign above array to jQuery variable.

Jquery Code :

var obj = '<?php echo json_encode($arr)?>';

when i print obj it gives me {"1":"10","5":"20"}. i want result in array like [1:10,5:20].

And after that i want to access array values by its key (e.g. obj[1] or obj[5])

Ignore my syntax error.

Thanks.

4
  • use json_decode() function Commented Jan 27, 2016 at 7:00
  • var encodedJson = '<?php echo json_encode($arr)?>'; var obj = $.parseJSON(encodedJson); alert(obj[1]); // this will show as 10 Commented Jan 27, 2016 at 7:04
  • 1
    @Vaira : Mr. Engineer wants to assign the php array to javascript variable. json_decode will convert the json data to php array. Not php array to json. Commented Jan 27, 2016 at 7:06
  • @VairaMuthu It does not help. Commented Jan 27, 2016 at 7:12

3 Answers 3

3

You just need to define var obj without usage of ' in script

<script>

var obj = <?php echo json_encode($arr)?>;
alert(obj[1]);// will alert 10

</script>
Sign up to request clarification or add additional context in comments.

Comments

1
 var data; //suppose data contains the json result i.e {"orders":[{"name":"Accessories"}}]
 var response_length=response.orders.length; //orders is the json array
  var array_store = [];
 for (i = 0; i < response_length; i++)
   array_store .push(response.orders[i].name); //name is json object

Comments

1

Simple Solution is as below:

var encodedJson = '<?php echo json_encode($arr)?>'; 
var obj = $.parseJSON(encodedJson); 
alert(obj[1]); // this will show as 10

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.