我想在“日期”字段中对以下标签进行排序,并计算“临时”字段的总和:
0 => array (size=3) 'id_cra' => string '4586' (length=4) 'temps' => string '03:00:00' (length=8) 'date' => string '2013-06-03' (length=10)
1 => array (size=3) 'id_cra' => string '4587' (length=4) 'temps' => string '03:00:00' (length=8) 'date' => string '2013-06-06' (length=10)
2 => array (size=3) 'id_cra' => string '4588' (length=4) 'temps' => string '03:00:00' (length=8) 'date' => string '2013-06-05' (length=10)
3 => array (size=3) 'id_cra' => string '4589' (length=4) 'temps' => string '03:00:00' (length=8) 'date' => string '2013-06-06' (length=10)
4 => array (size=3) 'id_cra' => string '4590' (length=4) 'temps' => string '03:00:00' (length=8) 'date' => string '2013-06-07' (length=10)
5 => array (size=3) 'id_cra' => string '4591' (length=4) 'temps' => string '02:00:00' (length=8) 'date' => string '2013-06-03' (length=10)
6 => array (size=3) 'id_cra' => string '4592' (length=4) 'temps' => string '03:30:00' (length=8) 'date' => string '2013-06-03' (length=10)
预期结果:
date => “Temps”字段的总和
2013-06-03 =>08:30:00
2013-06-06 =>06:00:00
等
PS:很抱歉,问一些对你来说可能很简单的事情,我已经在互联网上查了一下(比如这里:Sort array of objects by object fields),但我不明白答案
答案 0 :(得分:2)
我没试过,但必须是这样的:
$arr = [your array data]; // your array which has to be sorted
usort($arr, 'sort_array');
function sort_array($a, $b) {
$timeA = strtotime($a['date']);
$timeB = strtotime($b['date']);
if($timeA == $timeB) {
return 0;
}
return $timeA < $timeB ? -1 : 1;
}
计算总和将是对数组进行排序之后的循环,您必须按日期“分组”并总结“临时数”
答案 1 :(得分:1)
第一部分相当简单。我们可以使用array_multisort()
按字段对字段的数据进行排序,如下所示:
<?php
$data = array(
0 => array('id_cra' => '4586', 'temps' => '03:00:00', 'date' => '2013-06-03'),
1 => array('id_cra' => '4587', 'temps' => '03:00:00', 'date' => '2013-06-06'),
2 => array('id_cra' => '4588', 'temps' => '03:00:00', 'date' => '2013-06-05'),
3 => array('id_cra' => '4589', 'temps' => '03:00:00', 'date' => '2013-06-06'),
4 => array('id_cra' => '4590', 'temps' => '03:00:00', 'date' => '2013-06-07'),
5 => array('id_cra' => '4591', 'temps' => '02:00:00', 'date' => '2013-06-03'),
6 => array('id_cra' => '4592', 'temps' => '03:30:00', 'date' => '2013-06-03')
);
$tmp = array();
foreach($data as $k=>$r){
$tmp[] = $r['date'];
}
array_multisort($tmp,SORT_DESC,$data);
echo '<pre>',print_r($data),'</pre>';
但是现在想要为每一天添加时间。这并不困难,但您将失去id_cra
值。因此,对于下面的示例,我刚刚创建了一个新数组。如果您想要这样做,您应该能够使用这些信息将其构建回原始数组中。
date_default_timezone_set('America/New_York'); //set timezone
$midnight = mktime(0,0,0,date("n"),date("j"),date("Y")); // create a constant
$times = array();
foreach($data as $d){
// get number of secs since const
$time = strtotime(date("Y-m-d",$midnight).' '.$d['temps']) - $midnight;
if(isset($times[$d['date']])){
$times[$d['date']] += $time; // if day exists add secs
}else{
$times[$d['date']] = $time; // else set day with cur secs
}
}
foreach($times as $k=>&$time){
$time = date("Y-m-d H:i:s",strtotime($k)+$time); // reformat to date
}
echo '<pre>',print_r($times),'</pre>';