我希望PHP中的json_encode返回JSON数组,即使索引顺序不正确 [英] I would like json_encode in PHP to return a JSON array even if the indices are not in order

查看:267
本文介绍了我希望PHP中的json_encode返回JSON数组,即使索引顺序不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

但根据此内容: http://www.php .net/manual/en/function.json-encode.php#94157 不会.

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

我正在使用flot,所以我需要有一个返回数字索引的数组,但是我得到的是:

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

所以浮游物令人窒息.如果我在调用json_encode之前立即将数组var_dump删除,则它看起来像这样:

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

有什么想法吗?

推荐答案

正如zneak所说,Javascript(因此是JSON)数组不能具有乱序的数组键.因此,您要么需要接受将使用JSON对象(而不是数组),要么在json_encode之前调用array_values:

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

但是,您似乎希望使用flot显示时间序列数据.正如您在 flot时间序列示例中看到的那样,它应该是这样的两个元素数组:

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'}
  }
)

给出您的数组(我们称其为$data),我们可以像这样获得正确的JSON:

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

这篇关于我希望PHP中的json_encode返回JSON数组,即使索引顺序不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆