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

时间:2019-03-03 11:58:53

标签: php

我试图在我的示例通讯录中找到“最年长的人”。

这是地址簿数组:

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
        )
)

使用我的代码,我总是得到最后一个数组。

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

print_r($oldestPerson);

如何正确比较生日?

1 个答案:

答案 0 :(得分:4)

这应该可以解决问题:

$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);