如何选择具有最早时间的阵列

时间:2011-09-20 16:50:14

标签: php cakephp-1.3

我有这些arras

[0] => Array
        (
            [TEAM] => Array
                (
                    [id] => 5
                    [name] => localhost

                )

            [Registraion] => Array
                (

                     [Registered] => 2011-09-20 09:20:51
                )

        )

[1] => Array
        (
            [TEAM] => Array
                (
                    [id] => 6
                    [name] => localhost

                )

            [Registraion] => Array
                (

                     [Registered] => 2011-09-20 09:30:51
                )


        )

[2] => Array
        (
            [TEAM] => Array
                (
                    [id] => 7
                    [name] => localhost

                )

            [Registraion] => Array
                (

                     [Registered] => 2011-09-20 09:40:51
                )


        )

我想得到这个

[0] => Array
            (
                [TEAM] => Array
                    (
                        [id] => 5
                        [name] => localhost

                    )

                [Registraion] => Array
                    (

                         [Registered] => 2011-09-20 09:20:51
                    )

            )

因为那个人是最老的人。

如何获得最早的注册值?

感谢

3 个答案:

答案 0 :(得分:2)

$oldestkey = null;

foreach (array_keys($array) as $key) {
    if (isnull($oldestkey) || ($array[$key]['Registraion']['Registered'] < $array[$oldestkey]['Registraion']['Registered']) {
         $oldestkey = $key;
    }
}

请注意,您的密钥Registraion拼写错误,我猜它应该是Registration?另请注意,此代码不会处理具有相同注册时间的多个键的情况。它将挑选出第一个最早的时间并返回该记录的密钥。任何重复的时间都将被忽略。

答案 1 :(得分:1)

循环每个项目

 $oldest = $arr[0];
 foreach($array as $arr){ 
      if($arr["Registration"]["Registered"] < $oldest["Registration"]["Registered"])
            $oldest = $arr;
 }

比较时请使用时间比较

答案 2 :(得分:1)

function getOldestRecord($ar)
{
   $last_id;
   $last_time = 0;
   foreach($ar as $key => $val)
   {
      $time_stamp = strtotime($val['Registration']['Registered']);
      if($time_stamp > $last_time)
      {
         $last_time = $time_stamp;
         $last_id = $key;
      }
   }
   return $ar[$last_id];
}
上面的

函数接受你的数组,然后遍历它并比较日期,它将返回最后一个注册用户。