排序内部数组时间戳

时间:2018-07-10 02:31:28

标签: javascript php highcharts timestamp highstock

我有一个包含多个元素的数组,如下所示:

  {
"name": "DR",
"data": [
  [
    "1508112000000",
    4
  ],
  [
    "1534204800000",
    1
  ]
],
"type": "areaspline"
},
{
    "name": "SIT",
    "data": [
      [
        "1508112000000",
        4
      ],
      [
        "1534204800000",
        1
      ],
      [
        "1506384000000",
        3
      ],
      [
        "1534204800000",
        1
      ],
      [
        "1531094400000",
        1
      ],
      [
        "1528502400000",
        1
      ]
    ],
    "type": "areaspline"
  },

这是我用来将数据发送到高级图表中的确切格式,但是,问题是如果每个环境(DR,SIT)中的时间戳不正确,图表就会中断。

如何在每个环境中按时间戳对“数据”进行排序?

此JSON是用PHP生成的,并通过JavaScript发送。因此,我想知道如何在PHP或JavaScript中对数据进行排序。

谢谢。

1 个答案:

答案 0 :(得分:0)

一旦您了解了usort函数,这实际上是很简单的。它允许您定义自己的排序功能,因此可以根据传递2个对象的任何因素进行排序。

请注意,在您的示例json中,我必须在整个内容周围添加一组方括号,以使PHP用json_decode进行解析。

<?php

// note I had to add square brackets to your
// demo json ....

$json='[{
"name": "DR",
"data": [
  [
    "1508112000000",
    4
  ],
  [
    "1534204800000",
    1
  ]
],
"type": "areaspline"
},
{
    "name": "SIT",
    "data": [
      [
        "1508112000000",
        4
      ],
      [
        "1534204800000",
        1
      ],
      [
        "1506384000000",
        3
      ],
      [
        "1534204800000",
        1
      ],
      [
        "1531094400000",
        1
      ],
      [
        "1528502400000",
        1
      ]
    ],
    "type": "areaspline"
  }]';

$json_obj_arr=json_decode($json,true);

print_r($json_obj_arr);
print("\n\n");

// a function to handle the sorting itself
// usort will pass it an array(timestamp,datavalue) for both
// $a and $b so we compare the [0] element of each
function cmp($a, $b)
{
    if ($a[0] == $b[0]) {
        return 0;
    }
    return ($a[0] < $b[0]) ? -1 : 1;
}


// loop through the array, first is indexed
for($i=0;$i<count($json_obj_arr);$i++){
    // then each one of those contains an
    // associtive array with an element named ['data'] -
    // this is an indexed array that you want sorted
    // on the [0] element

    usort($json_obj_arr[$i]['data'],"cmp");
}

print_r($json_obj_arr);
print("\n\n");
?>