用php获得下一个生日

时间:2017-07-23 10:51:09

标签: php arrays json

我有一个存储生日数据的json。

    {
    "user": [
          {
    "id": "1",
    "name": "Tom",
    "bday": {
          "month": "1",
          "day": "23"
          }
    },
    {
    "id": "2",
    "name": "Tommy",
    "bday": {
          "month": "1",
          "day": "28"
          }
    },
    {
    "id": "3",
    "name": "Mary",
    "bday": {
          "month": "1",
          "day": "30"
          }
    },
    {
    "id": "4",
    "name": "Kelvin",
    "bday": {
          "month": "1",
          "day": "1"
          }
    },
    {
    "id": "5",
    "name": "Peter",
    "bday": {
          "month": "1",
          "day": "1"
          }
    }
    ]
    }

我想要一个函数返回今天或下一个生日的用户。 例如,今天是1月21日(01-21),它将返回Tom(01-23),如果今天是1月1日,它将返回Peter和Kelvin(01-01)。

这是我的想法,但我不知道如何在PHP中这样做... 我认为这不是最好的解决方案。还有更好的主意吗?

function findBday($today){
$month = today's month;
$day = today's day;

//make a loop
if($month == $bday[month] && $day == $bday[day]){
// put the result into array
} else {
//put $month - $bday[month] , $day - $bday[day]  and add the smallest one into array 
and sort them;
//if today is December and no one birthday in this month , find January 
  }
return $array;
}

4 个答案:

答案 0 :(得分:1)

希望这会对你有所帮助。我有与你描述的相同的逻辑:

$json = '{
    "user": [
          {
    "id": "1",
    "name": "Tom",
    "bday": {
          "month": "1",
          "day": "23"
          }
    },
    {
    "id": "2",
    "name": "Tommy",
    "bday": {
          "month": "1",
          "day": "28"
          }
    },
    {
    "id": "3",
    "name": "Mary",
    "bday": {
          "month": "1",
          "day": "30"
          }
    },
    {
    "id": "4",
    "name": "Kelvin",
    "bday": {
          "month": "1",
          "day": "1"
          }
    },
    {
    "id": "5",
    "name": "Peter",
    "bday": {
          "month": "1",
          "day": "1"
          }
    }

    ]
    }';
$birthday_array = json_decode($json,true);
//var_dump($bir_array);
$result = findBday($birthday_array['user']);
var_dump($result);


function findBday($user_details){
    $this_month = date("n");
    $this_day = date("j");
    $return_array = array();
    $tmp_array = array();
    //make a loop
    foreach ($user_details as $user_detail) {        
        $bday = $user_detail['bday'];
        if($this_month == $bday['month'] && $this_day == $bday['day']){
            $return_array[] = $user_detail['name'] . "(".$bday['day']."-".$bday['month'].")";
        } 
        else {
            $tmp_array[] =  $user_detail;
          }
    }
    if(count($return_array) === 0 && count($tmp_array) > 0)
    {

        //sort using php usort
        usort ($tmp_array, 'sortByOrder'); 
        $closest = null;        
        $tmp_val = "";
        foreach ($tmp_array as $key => $value) {
            $month = $value['bday']['month'];
            $day = $value['bday']['day'];
            if($month == $this_month)
            {
                if($day > $this_day){
                    $tmp_val = $value;
                    break;
                }
            }
            elseif ($month > $this_month) {
                $tmp_val = $value;
                break;
            }
        }      
        if($tmp_val != "")
            $tmp_array = $tmp_val;
        else    
            $tmp_array = $tmp_array[0];
        $bday = $tmp_array['bday'];
        $return_array[] = $tmp_array['name'] . "(".$bday['day']."-".$bday['month'].")";

    }


    return $return_array;
}
function sortByOrder($a, $b) {    
    $day_a = $a['bday'];
    $day_b = $b['bday'];
    if ($day_a['month'] > $day_b['month'])
        return 1;
    elseif($day_a['month'] == $day_b['month'])
    {
        if ($day_a['day'] > $day_b['day'])   
            return 1;
    }

}

答案 1 :(得分:0)

在这里你拥有它:

function findNextBday($userData) {
    $today = Date('Y-m-d');
    $difference = 0;
    $soonest = [];

    foreach($userData as $user) {
        $y = $user['bday']['month'] < Date('m') ? Date('Y')+1 : Date('Y');
        $bday = $y . '-' . $user['bday']['month'] . '-' . $user['bday']['day'];
        $temp = strtotime($today) - strtotime($bday);

        if($difference == 0 || $temp > $difference) {
            $difference = $temp;
            $soonest = [$user];
        }else if($temp == $difference) {
            $soonest[] = $user;
        }
    }

    return $soonest;
}

$data = json_decode($json, true);

$nextBirthday = findNextBday($bdays['user']); 
var_dump($nextBirthday);// Will return an array of the users with the soonest birthdays

说明:

  • 该函数循环遍历每个用户并计算下一个完整生日日期。由于数据只有月和日,$y计算年份,因此我们可以有一个有效的日期来进行操作。
  • 我们与今天的日期有所不同,并将其与之前存储的差异进行比较。
  • 如果大于,则意味着 生日更快;所以我们覆盖先前存储的差异并重置$soonest数组,其中生日是最接近的用户。
  • 如果与今天的日期的差异与先前存储的相同,则意味着这些用户具有相同的生日,因此我们只是将该用户附加到该数组。

答案 2 :(得分:0)

此代码查找将来有生日并将其存储在$ next_bdays中的所有用户。您只需要根据需要对它们进行排序。

$data = json_decode($json);

$next_bdays = array();
$today = date('Y-n-d');
foreach($data as $users)
{
    foreach($users as $u)
    {
        $bday = $u->bday;
        $birthday = date('Y').'-'.$bday->month.'-'.$bday->day;

        if(date($birthday)>=$today )
        {
            $next_bdays = array('bday' => $birthday, 'name' => $u->name, 'id' => $u->id);
        }
    }
}

答案 3 :(得分:-2)

class BirthDayUsers
{
    private $birthDayUsers = [];

    public function __construct(array $users)
    {
        foreach ($users as $user) {
            $this->birthDayUsers[] = [
                'name' => $user['name'],
                'bday' => new DateTime($user['bday']['month'] . '/' . $user['bday']['day'])
            ];
        }
        usort($this->birthDayUsers, function ($birthDayUser1, $birthDayUser2) {
            return $birthDayUser1['bday']->diff($birthDayUser2['bday'])->invert;
        });
    }

    public function findBy(DateTimeInterface $today): array
    {
        foreach ($this->birthDayUsers as $birthDayUser) {
            if ($today->diff($birthDayUser['bday'])->invert) {
                continue;
            }

            return array_filter($this->birthDayUsers, function ($user) use ($birthDayUser) {
                return $user['bday']->diff($birthDayUser['bday'])->days == 0;
            });
        }
        return [];
    }
}

用法:

$ birthDayUsers = new BirthDayUsers($ json [&#39; user&#39;]);

$ birthDayUsers-&gt; findBy(new DateTime(&#39; 1/1&#39;));

$ birthDayUsers-&gt; findBy(new DateTime(&#39; 1/2&#39;));