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

醉酒当歌 提交于 2019-11-30 12:18:16

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)
  )
);

It's conceptually impossible. You cannot encode an array with fixed indices in JSON.

As a reminder, a JSON array looks like this:

[1, 2, 3, 4, 5]

There's no room to put indices there.

You should work on the Javascript side. Accepting that json_encode will return an object, you can convert this object into an array. That shouldn't be too hard.

function toArray(object)
{
    var result = [];
    for (var key in object)
    {
        if (!key.match(/^[0-9]+$/)) throw new Error("Key must be all numeric");
        result[parseInt(key)] = object[key];
    }
    return result;
}

You can force json_decode() to produce arrays by passing TRUE as the second parameter, but you can't force json_encode() to produce arrays in the first place:

json_decode($json, TRUE); // force array creation

You can use array_merge to reindex a numerically indexed array, like this:

$a = array(2 => 3, 4 => 5);
$a = array_merge($a);
var_dump($a);

For flot, what you're asking for isn't actually what you want. You want an array of arrays, not an array of numbers. That is, you want something that looks like this:

  [[1281830400, 34910],
   [1281916800, 45385],
   [1282003200, 56928],
   [1282089600, 53884],
   [1282176000, 50262],
   [1281657600, 45446],
   [1281744000, 34998]]

As for how to do that in PHP, I'm not sure.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!