user485498
user485498

Reputation:

2-dimensional JSON array to PHP

I have a JSON encoded array that looks like this (it came from a 2d PHP string array):

[
[
    "a1",
    "a2",
    "a3",
    "a4"
],
[
    "b1",
    "b2",
    "b3",
    "b4"
],
[
    "c1",
    "c2",
    "c3",
    "c4"
]
]

It has been validated on http://jsonlint.com/

Now I want to send this array to another page by Ajax and convert it back to a 2d PHP array. After making a JSON array I do the following (where myJsonArray is the name I gave to the array after making it into a Javascript array.:

$.ajax({
       type: "GET",
       url: "somewhere.php",
       data: {jsonArray : myJsonArray},
       dataType: "json",
       success: function(msg){
         alert( msg); 
       }

     });
 }

And then in somewhere.php I do:

 $json_array = $_GET['jsonArray'];

 $myArray = json_decode($json_array,true);

But when I echo the result I just get

[Object object]

I'm not sure how to recreate the PHP array.

EDIT: How to make myJsonArray:

<?php
$array = json_encode($original_array);

echo "var myJsonArray = ". $array . ";\n";
?>

I would also like to point out that for tesitng purposes, in the alert box I made it print myJsonArray on success, and it did indeed print out the array as expected.

Upvotes: 1

Views: 1326

Answers (2)

Rubin Porwal
Rubin Porwal

Reputation: 3845

I have tried executing below code snippet for decoding json content as specified above and it is working fine for me.

<?php
               $a=array(array("a1","a2","a3","a4"),array("b1","b2","b3","b4"),array("c1","c2","c3","c4"));
               $json_content=json_encode($a);
              $json_array=json_decode($json_content,true);
               echo '<pre>';
                print_r($json_array);
?>

Upvotes: -1

Adam Lockhart
Adam Lockhart

Reputation: 1195

"[Object object]" is javascript evaluating an object as a string.

When you pass the optional "true" into json_decode, you are telling it that it is an associative array. But you really want an array of arrays.

I am sure that if you use JSON.stringify to print to your log, you would have the correct data, except the outer brackets would be "{..}".

Upvotes: 2

Related Questions