0

I have this kind of array:

array {
    [0] => {"ID":"343","name":"John","money":"3000"}
    [1] => {"ID":"344","name":"Erik","money":"2000"}
    [2] => {"ID":"346","name":"Ronny","money":"3300"}
}

And I want to read it from PHP to JavaScript with JSON. As you can see, the inner array is already encoded as follows:

json_encode($a)

To be readable from my JavaScript code, I want it with the following syntax:

"[0]" : "{"ID":"343","name":"John","money":"3000"}",
"[1]" : "{"ID":"344","name":"Eric","money":"2000"}",
"[2]" : "{"ID":"345","name":"Ronny","money":"3300"}",

How can I do that?

3
  • 1
    php json_encode() will be decoded by jquery jQuery.parseJSON() Commented Sep 24, 2015 at 12:07
  • 1
    Use jsonlint.com to validate you JSON - I see some problems. Commented Sep 24, 2015 at 12:10
  • 1
    Usually doesn't make sense to encode the inner arrays by themselves. Is there a reason for doing that instead of encoding everything at once? Commented Sep 24, 2015 at 12:19

2 Answers 2

3

In your title, you ask How to encode with a JSON multidimensional array. I am going to assume that is your real question, because your question body asks something different. Assuming you have an array $arr, do not call json_encode() on each inner array $a.

Instead, simply call json_encode($arr) and it will encode the entire array, including inner arrays.

$arr = array (

    array ("ID" => "343", "name" => "John", "money" => "3000"),
    array ("ID" => "344", "name" => "Erik", "money" => "2000"),
    array ("ID" => "346", "name" => "Ronny", "money" => "3300")

);

$j = json_encode($arr);

$j will be something like this:

[{"ID":"343","name":"John","money":"3000"},
{"ID":"344","name":"Erik","money":"2000"},
{"ID":"346","name":"Ronny","money":"3300"}]

You can parse this quite easily using jQuery.parseJSON(). Then you can simply loop through the parsed array to get what you want from the inner arrays.

var arr = jQuery.parseJSON('[{"ID":"343","name":"John","money":"3000"},{"ID":"344","name":"Erik","money":"2000"},{"ID":"346","name":"Ronny","money":"3300"}]');

for(var i = 0; i < arr.length; i++) {
    var a = arr[i]; // Inner array.

    console.log(a.ID);
    console.log(a.name);
    console.log(a.money);
}
Sign up to request clarification or add additional context in comments.

Comments

2
$arr = array(
      '[0]' => '{"ID":"343","name":"John","money":"3000"}',
      '[1]' => '{"ID":"344","name":"Erik","money":"2000"}',
      '[2]' => '{"ID":"346","name":"Ronny","money":"3300"}'
     );
echo json_encode($arr);

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.