我目前正在使用以下json数据。 (关键是时间hh:mm)
"chart": {
"23:20": 11,
"23:30": 11,
"23:40": 11,
"23:50": 16,
"00:00": 16,
"00:10": 14,
"00:20": 11,
"00:30": 12,
"00:40": 14,
"00:50": 10,
"01:00": 8,
"01:10": 12,
"01:20": 15,
"01:30": 13,
"01:40": 11,
"01:50": 8,
"02:00": 8
}
然后我将数据移动到php数组。我想对数组进行排序,因此它从当前服务器时间开始并从那里继续。
目前我正在使用以下php(未排序)
<?php
foreach ($data['chart'] as $key => $value){
echo 'Time: '.$key.'Data: '.$value;
}
?>
答案 0 :(得分:0)
最简单的方法可能是过滤掉所有过早的&#34;条目首先使用array_filter()
,然后使用ksort()
对结果数组进行排序:
<?php
function getFilter($server_time) {
return function($item) use($server_time) {
return (strtotime($item) >= $server_time);
};
}
$data = '{"chart": {
"23:20": 11,"23:30": 11,"23:40": 11,"23:50": 16,"00:00": 16,
"00:10": 14,"00:20": 11,"00:30": 12,"00:40": 14,"00:50": 10,
"01:00": 8,"01:10": 12,"01:20": 15,"01:30": 13,"01:40": 11,
"01:50": 8,"02:00": 8
}}';
$json = json_decode($data, true);
$src = $json['chart'];
$server_time = strtotime("now");
$filtered = array_filter($src, getFilter($server_time), ARRAY_FILTER_USE_KEY);
ksort($filtered);
print_r($filtered);
实时测试案例:https://3v4l.org/M3RLm
答案 1 :(得分:0)
试一试:
$data = json_decode('{"chart": {
"23:20": 11,
"23:30": 11,
"23:40": 11,
"23:50": 16,
"00:00": 16,
"00:10": 14,
"00:20": 11,
"00:30": 12,
"00:40": 14,
"00:50": 10,
"01:00": 8,
"01:10": 12,
"01:20": 15,
"01:30": 13,
"01:40": 11,
"01:50": 8,
"02:00": 8
}}');
$data = (array) $data->chart;
function sort_time($a, $b) { return strtotime($a) > strtotime($b); }
uksort($data, 'sort_time' );
foreach ($data as $key => $value) {
echo "$key: $value\n";
}
答案 2 :(得分:-1)
function hsort($a, $b) // callback function for uksort function
{
return (floatval(str_replace(":", ".", $a)) - floatval(str_replace(":", ".", $b))) // convert each time to float value, like '01:56'-> "01.56", then compare values as float
}
$chart = array_flip($chart); // flip indexes with values to get ability to operate with indexes as array values (which are time in your array)
uksort($chart, "hsort"); // sort time values
$chart = array_flip($chart); // flip again to make time values as index again