如何在数组中找到最大值和最小值以及相应的日期

时间:2014-09-06 08:57:31

标签: php arrays

我有一个数组,我想要一些输出

Array
    (
[0] => Array
    (
        [DaySession1] => 
        [DaySession] => 
        [SubmitSessionDate] => 
        [id] => 
    )

[1] => Array
    (
        [DaySession2] => 
        [DaySession] => 
        [SubmitSessionDate] => 
        [id] => 
    )

[2] => Array
    (
        [DaySession3] => 2
        [DaySession] => 2
        [SubmitSessionDate] => 2014-09-03 23:58:56
        [id] => 2120
    )

[3] => Array
    (
        [DaySession4] => 10
        [DaySession] => 10
        [SubmitSessionDate] => 2014-09-04 00:06:39
        [id] => 2121
    )

[4] => Array
    (
        [DaySession5] => 
        [DaySession] => 
        [SubmitSessionDate] => 
        [id] => 
    )

[5] => Array
    (
        [DaySession6] => 
        [DaySession] => 
        [SubmitSessionDate] => 
        [id] => 
    )

[6] => Array
    (
        [DaySession7] => 6
        [DaySession] => 6
        [SubmitSessionDate] =>  2014-09-05 00:06:39
        [id] => 
    )

这是我即将推出的数组我希望从上面的数组中获得最大[DaySession]值,并且还需要相应的[SubmitSessionDate]

同样的事情我也想从上面的数组和相应的[SubmitSessionDate]获得最小[DaySession]值?

结果应该是:

Maximum Day session = 10 and SubmitSessionDate = 2014-09-04 00:06:39
Minimum Day Session =2  and SubmitSessionDate = 2014-09-03 23:58:56 

1 个答案:

答案 0 :(得分:2)

您可以获得一天的会话及其密钥,然后从那里开始,您可以使用reset()end()。示例:Demo

$keys = array();
foreach($array as $key => $val) {
    if(!empty($val['DaySession'])) {
        $keys[$val['DaySession']] = $key;
    }
}

ksort($keys);
$min_key = reset($keys);
$max_key = end($keys);

echo "Maximum Day session = ".$array[$max_key]['DaySession']." and SubmitSessionDate = ".$array[$max_key]['SubmitSessionDate']." <br/>";
echo "Minimum Day session = ".$array[$min_key]['DaySession']." and SubmitSessionDate = ".$array[$min_key]['SubmitSessionDate'];