duanmo6937 2019-03-03 11:58
浏览 233
已采纳

从数组dd / mm / yy获取最早的日期

i try to get the "oldest person" in my example address book.

This is the address book array:

Array
(
    [0] => Array
        (
            [Firstname] => Bill
            [Lastname] => McKnight
            [Gender] => Male
            [Birthday] => 16/03/77
        )

    [1] => Array
        (
            [Firstname] => Paul
            [Lastname] => Robinson
            [Gender] => Male
            [Birthday] => 15/01/85
        )

    [2] => Array
        (
            [Firstname] => Gemma
            [Lastname] => Lane
            [Gender] => Female
            [Birthday] => 20/11/91
        )

    [3] => Array
        (
            [Firstname] => Sarah
            [Lastname] => Stone
            [Gender] => Female
            [Birthday] => 20/09/80
        )

    [4] => Array
        (
            [Firstname] => Wes
            [Lastname] => Jackson
            [Gender] => Male
            [Birthday] => 14/08/74
        )
)

With my code I get always the last array..

$oldestPerson = 0;
for($i=0; $i<count($persons);$i++){
    if($persons[$i]['Birthday'] > $persons[$i+1]['Birthday']){
        $oldestPerson = $persons[$i];
    }
}

print_r($oldestPerson);

How can I compare correctly the birthdays?

  • 写回答

1条回答 默认 最新

  • douxiong5438 2019-03-03 12:09
    关注

    This should do the trick:

    $oldestPerson = null;
    $oldestBirthday = new DateTime();  // preparing to save the oldest found birthday to compare against
    
    for($i=0; $i<count($persons);$i++){
        // create a DateTime Object out of the birthday-string
        $birthday = DateTime::createFromFormat("d/m/y", $persons[$i]['Birthday']);
    
        if($birthday < $oldestBirthday){  // compare this to the oldest (=smallest) saved one
            $oldestPerson = $persons[$i]; // update
            $oldestBirthday = $birthday;  // update
        }
    }
    
    print_r($oldestPerson);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路