سؤال

Using json_encode to encode an array of dates, it sometimes does one thing, sometimes does another.

For example, if I'm trying to encode something like:

array(6) {
  [0]=>
  string(6) "Jun-24"
  [1]=>
  string(6) "Jun-25"
  [2]=>
  string(6) "Jun-28"
  [3]=>
  string(11) "Training-24"
  [4]=>
  string(6) "Jun-29"
  [5]=>
  string(6) "Jun-30"
}

It will output

["Jun-24","Jun-25","Jun-28","Training-24","Jun-29","Jun-30"]

However, when I try to encode something like:

array(17) {
  [0]=>
  string(6) "Jun-23"
  [1]=>
  string(6) "Jun-24"
  [2]=>
  string(6) "Jun-28"
  [3]=>
  string(11) "Training-24"
  [4]=>
  string(6) "Jun-29"
  [5]=>
  string(6) "Jun-30"
  [6]=>
  string(6) "Jul-06"
  [7]=>
  string(6) "Jul-07"
  [9]=>
  string(6) "Jul-09"
  [10]=>
  string(6) "Jul-16"
  [11]=>
  string(6) "Jul-17"
  [12]=>
  string(6) "Jul-20"
  [13]=>
  string(6) "Jul-23"
  [14]=>
  string(6) "Jul-24"
  [15]=>
  string(6) "Jul-30"
  [16]=>
  string(6) "Aug-01"
  [17]=>
  string(6) "Aug-05"
}

It will output

{"0":"Jun-23","1":"Jun-24","2":"Jun-28","3":"Training-24","4":"Jun-29","5":"Jun-30","6":"Jul-06","7":"Jul-07","9":"Jul-09","10":"Jul-16","11":"Jul-17","12":"Jul-20","13":"Jul-23","14":"Jul-24","15":"Jul-30","16":"Aug-01","17":"Aug-05"}

(Sorry, couldn't find a smaller example where it fails)

Point being, why does it do this? The options are the same, the array is structured the same, what's the issue?

هل كانت مفيدة؟

المحلول

Your PHP array is missing entry 8, so is a mapping (object) and not a list (array).

نصائح أخرى

You don't have key [8] set in your second example. According to the documentation a sequential array with an unset key will be encoded as a JSON object and not a JSON array.

In your first example the array is numbered sequentially from zero. PHP treats this as a conventional array and encodes it accordingly.

In your second example element 8 is missing. PHP treats this as an associative array and encodes the keys accordingly.

It is because of the indexing issue, when your index is not proper it will behave like this.

the best way to resolve is reindexing.

$array = array_values($array);

Do like this just before converting to JSON.

Just when you encode the array, do this which will reindex array values:

$encoded = json_encode(array_values($myArray));
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top