首先你需要确定你是否需要插入相关数据以及你插入的数据的方案,如果你不能确定中间缺失的shijian字段的始末的话,需要遍历这个数组去确定,然后将没有的字段加进去,然后用usort进行排序。
也可以在插入的时候决定你插入的位置,但是由于你插入会影响你数组的下标,所以还是上面第一个方法比较方便。
参考代码
$max_shijian = date("H");
// 填充主方法
$fill_date = function ($input,$key) use($max_shijian) {
$hours = range(0,$max_shijian);
$riqi = null;
// 筛选出不存在的时间
// http://php.net/manual/zh/function.array-map.php
array_map(function(&$item,$key) use(&$hours,&$riqi){
empty($riqi) and $riqi = $item['riqi'];
unset($hours[intval($item['shijian'])]);
},$input);
// 填充不存在的时间
foreach ($hours as $hour) {
$input[] = [
'key' => $key,
'riqi' => $riqi,
'shijian' => getFullHour($hour),
'num' => 0,
];
}
// 排序
// http://php.net/manual/zh/function.usort.php
usort($input,function($a,$b){
return (intval($a['shijian'])
});
return $input;
};
// 将小时补全为2位
function getFullHour($hour){
return (strlen($hour)==1)?("0".$hour):$hour;
}
$json = '{"site001":[{"key":"site001","riqi":"2016-06-14","shijian":"00","num":"10"},{"key":"site001","riqi":"2016-06-14","shijian":"01","num":"4"},{"key":"site001","riqi":"2016-06-14","shijian":"02","num":"1"},{"key":"site001","riqi":"2016-06-14","shijian":"03","num":"3"},{"key":"site001","riqi":"2016-06-14","shijian":"04","num":"2"},{"key":"site001","riqi":"2016-06-14","shijian":"05","num":"1"},{"key":"site001","riqi":"2016-06-14","shijian":"07","num":"9"},{"key":"site001","riqi":"2016-06-14","shijian":"08","num":"2"}],"site002":[{"key":"site002","riqi":"2016-06-14","shijian":"00","num":"3"},{"key":"site002","riqi":"2016-06-14","shijian":"01","num":"13"},{"key":"site002","riqi":"2016-06-14","shijian":"02","num":"8"},{"key":"site002","riqi":"2016-06-14","shijian":"03","num":"23"},{"key":"site002","riqi":"2016-06-14","shijian":"04","num":"14"},{"key":"site002","riqi":"2016-06-14","shijian":"05","num":"6"},{"key":"site002","riqi":"2016-06-14","shijian":"06","num":"4"},{"key":"site002","riqi":"2016-06-14","shijian":"07","num":"7"},{"key":"site002","riqi":"2016-06-14","shijian":"08","num":"18"},{"key":"site002","riqi":"2016-06-14","shijian":"09","num":"6"}],"site003":[{"key":"site003","riqi":"2016-06-14","shijian":"00","num":"1"},{"key":"site003","riqi":"2016-06-14","shijian":"04","num":"2"},{"key":"site003","riqi":"2016-06-14","shijian":"07","num":"6"}],"site004":[{"key":"site004","riqi":"2016-06-14","shijian":"00","num":"3"},{"key":"site004","riqi":"2016-06-14","shijian":"02","num":"1"},{"key":"site004","riqi":"2016-06-14","shijian":"03","num":"4"},{"key":"site004","riqi":"2016-06-14","shijian":"04","num":"7"},{"key":"site004","riqi":"2016-06-14","shijian":"05","num":"4"},{"key":"site004","riqi":"2016-06-14","shijian":"06","num":"2"}]}';
$data = json_decode($json,true);
foreach ($data as $key => $value) {
$data[$key] = call_user_func($fill_date,$value,$key);
}
print_r($data);
?>