Robbert
Robbert

Reputation: 1330

json_encode multidimensional array encodes to object instead of array

I try to encode 2 arrays in a multidimensional array with the same structure (see below), but they are encoded differently.

The only difference is that the second array has more elements in the options array (27 elements) than the first one (3 elements).

The first one encodes the options array as an array:

{"structure":[{"options":[{"label":"Label 1","value":"value-1"},{"label":"Label 2","value":"value-2"},{ ... etc

The second one encodes it as an object:

{"structure":[{"options":{"0":{"label":"Label 3","value":"value-3"},"1":{"label": "Label 4" ... etc

Now I try to use this JSON object as input for a Javascript script. The first one works and is interpreted as an array of objects, but the second one is interpreted as an object (so not iterable).

Does json_encode() have a flag to always force array structure (just as it has for force object) or do I have to create a custom function?

Array structure:

array(2) {
  ["structure"]=>
  array(9) {
    [1]=>
    array(3) { // Array 1 <-------
      ["options"]=>
      array(3) {
        [0]=>
        array(2) {
          ["label"]=>
          string(7) "Label 1"
          ["value"]=>
          string(7) "value-1"
        }
        [1]=>
        array(2) {
          ["label"]=>
          string(9) "Label 2"
          ["value"]=>
          string(9) "value-2"
        }
        ...
      }
    }
    [2]=>
    array(3) { // Array 2 <------
      ["options"]=>
      array(27) { 
        [0]=>
        array(2) {
          ["label"]=>
          string(13) "Label 3"
          ["value"]=>
          string(13) "value-3"
        }
        [1]=>
        array(2) {
          ["label"]=>
          string(11) "Label 4"
          ["value"]=>
          string(11) "value-4"
        }
        ...
    }
  }
}

Upvotes: 0

Views: 213

Answers (1)

Robbert
Robbert

Reputation: 1330

With help of the comment of @Uwe and this question, I found out that the problem occurred because there was (for some reason) an array index element skipped. When this happens json_encode() creates this object structure instead of an array.

To fix this I reindexed the options array with array_values() and that fixed my problem.

Upvotes: 1

Related Questions