我希望PHP中的json_encode返回一个JSON数组,即使索引不是有序的

And*_*son 11 php json jsonp flot

但根据这个:http://www.php.net/manual/en/function.json-encode.php#94157它不会.

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

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

所以flot窒息.如果我在调用json_encode之前对数组进行var_dump,它看起来像这样:

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

有任何想法吗?

pr1*_*001 30

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

json_encode(array_values($data));
Run Code Online (Sandbox Code Playgroud)

但是,看起来您正在寻找使用flot显示时间序列数据.正如您在flot时间序列示例中所看到的,它应该是一个两元素数组,如下所示:

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

给定你的数组(让我们称之为$data)我们可以得到正确的JSON,如下所示:

json_encode(
  array_map(
    function($key, $value) { return array($key, $value); },
    array_keys($data),
    array_values($data)
  )
);
Run Code Online (Sandbox Code Playgroud)


zne*_*eak 7

这在概念上是不可能的.您不能使用JSON中的固定索引编码数组.

提醒一下,JSON数组如下所示:

[1, 2, 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)

那里没有放置指数的空间.

你应该在Javascript方面工作.接受json_encode它将返回一个对象,您可以将此对象转换为数组.这应该不会太难.

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;
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*c B 5

您可以json_decode()通过传递TRUE作为第二个参数来强制json_encode()生成数组,但是您不能强制首先生成数组:

json_decode($json, TRUE); // force array creation
Run Code Online (Sandbox Code Playgroud)