I would like json_encode in PHP to return a JSON array even if the indices are not in order

Andrew Watson picture Andrew Watson · Aug 24, 2010 · Viewed 25.5k times · Source

but according to this: http://www.php.net/manual/en/function.json-encode.php#94157 it won't.

I'm using flot so I need to have an array with numeric indexes returned but what I'm getting is this:

jsonp1282668482872 ( {"label":"Hits 2010-08-20","data":{"1281830400":34910,"1281916800":45385,"1282003200":56928,"1282089600":53884,"1282176000":50262,"1281657600":45446,"1281744000":34998}} );

so flot is choking. If I var_dump the array right before I call json_encode it looks like this:

array(7) {
  [1281830400]=>
  int(34910)
  [1281916800]=>
  int(45385)
  [1282003200]=>
  int(56928)
  [1282089600]=>
  int(53884)
  [1282176000]=>
  int(50262)
  [1281657600]=>
  int(45446)
  [1281744000]=>
  int(34998)
}

any ideas?

Answer

pr1001 picture pr1001 · Aug 24, 2010

As zneak says, Javascript (and thus JSON) arrays cannot have out-of-order array keys. Thus, you either need to accept that you'll be working with JSON objects, not arrays, or call array_values before json_encode:

json_encode(array_values($data));

However, it looks like you're looking to display time series data with flot. As you can see on the flot time series example, it should be a two element array like so:

$.plot(
  $('#placeholder'),
  [[
    [1281830400, 34910],
    [1281916800, 45385],
    [1282003200, 56928],
    [1282089600, 53884],
    [1282176000, 50262],
    [1281657600, 45446],
    [1281744000, 34998]
  ]],
  {
    label: 'Hits 2010-08-20',
    xaxis: {mode: 'time'}
  }
)

Given your array (let's call it $data) we can get the proper JSON like so:

json_encode(
  array_map(
    function($key, $value) { return array($key, $value); },
    array_keys($data),
    array_values($data)
  )
);