1

I've looked around but haven't found an answer so I figured i would give it an ask myself.

I've noticed that a round trip to JSON converts a 2-D array into a 1D array of Objects.

Is there any way around this or should I just try to work with objects from the beginning (e.g. $test->1->4 ? see example below

    $test = array();
    $test[0][0] = "0-0";
    $test[0][2] = "0-2";
    $test[1][1] = "1-1";
    $test[1][2] = "1-2";
    var_dump($test);
    $encoded = json_encode($test);
    var_dump($encoded);
    $recreated = json_decode($encoded);
    var_dump($recreated);

outputs

array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(3) "0-0"
    [2]=>
    string(3) "0-2"
  }
  [1]=>
  array(2) {
    [1]=>
    string(3) "1-1"
    [2]=>
    string(3) "1-2"
  }
}
string(45) "[{"0":"0-0","2":"0-2"},{"1":"1-1","2":"1-2"}]"
array(2) {
  [0]=>
  object(stdClass)#19 (2) {
    ["0"]=>
    string(3) "0-0"
    ["2"]=>
    string(3) "0-2"
  }
  [1]=>
  object(stdClass)#20 (2) {
    ["1"]=>
    string(3) "1-1"
    ["2"]=>
    string(3) "1-2"
  }
}

3 Answers 3

2

This is because you don't have ongoing indexes in your array:

$test = array();
$test[0][0] = "0-0";
$test[0][2] = "0-2";

In this case json_encode() HAS to create an object because there is a numeric key (1) missing.

You can decode it back to an array with json_decode($txt, true), but this is only a work around, not a fix.

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

2 Comments

THanks for the answer, that worked. In my particular application, it will be a 256x256 array but chances are every index won't be set. Would it be better to work with objects in the first place? Is there a performance difference?
There is no real performance difference on the JS side. On the PHP side there may be a small difference, but I would use arrays with json_decode($txt, true) or set the non-existing indexes to NULL - dunno what fits your needs.
0

By default json_decode will convert the json into objects. You code needs to look like:

$recreated = json_decode($encoded, true);

Comments

0

You can decode as arrays:

$recreated = json_decode($encoded, true);

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.