foreach循环忽略数组顺序

时间:2019-11-15 17:31:42

标签: php arrays sorting

我试图将一组不同的对象组合在一起。他们是工作面试。我希望按职务分类,然后按时间分组。从最新到最早。到目前为止,一切都很好。进行我想做的事情的方法可能要复杂得多,但是下面的代码对我有用,直到要求我将最近的面试日期放在首位。

function interview_sort($interviews) {

    $titles = get_job_titles();

    foreach($interviews as $interview) {

        if(strtotime($interview->getStart()) > strtotime('-2 weeks')) {

            // get all the interview times no more than two weeks old
            $times[] = strtotime($interview->getStart());

        }
    }

    // we only want one of each
    $times = array_unique($times);

    // sort them from latest to earliest
    rsort($times);

    // we want the closest date first
    $closest = find_closest_date($times, strtotime('today'));

    //store it
    $date = $times[$closest];

    // bin it from it's original position
    unset($times[$closest]);

    // put it on the front
    array_unshift($times, $date);

    print_r($times);

    // group by job title
    foreach ($titles as $title) {

        // group by interview time
        foreach($times as $time) {

            foreach ($interviews as $interview) {

                if($interview->getPostingTitle() == $title && strtotime($interview->getStart()) == $time) {

                    $grouped[$title][$time][] = $interview;
                }
            }
        }
    }
    return $grouped;
}

写入print_r($times)的时间点将输出数组,该数组的第一个时间为最接近的时间,然后根据需要从最近到最早的时间为随后的时间。但是,$grouped数组的最新顺序是最早的。

1 个答案:

答案 0 :(得分:0)

您尚未在foreach循环之前声明该数组。

function interview_sort($interviews) {

    $times = [];
    $titles = get_job_titles();

    foreach($interviews as $interview) {

        if(strtotime($interview->getStart()) > strtotime('-2 weeks')) {

            // get all the interview times no more than two weeks old
            $times[] = strtotime($interview->getStart());

        }
    }
[...]