【问题标题】:foreach loop ignoring array orderforeach 循环忽略数组顺序
【发布时间】:2020-03-11 21:38:50
【问题描述】:

我有一堆不同的对象,我试图将它们组合在一起。他们是工作面试。我希望他们按职位分组,然后按时间分组。从最新到最早。到目前为止,一切都很好。可能有一种不那么复杂的方式来做我正在尝试的事情,但以下代码对我有用,直到我被要求将最近的面试日期放在首位。

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 数组的原始顺序是从最新到最早。

【问题讨论】:

  • 我认为您仍在按标题顺序将项目添加到数组中。因此,如果最近的采访在标题 3 中,则循环实际上会在标题 1 中显示最新到最旧的采访,然后是标题 2,然后只有在标题 3 中,您才会首先找到最接近的采访。
  • 如果数据需要首先按最近采访的标题分组,则需要首先包含包含最近采访的整个标题。

标签: php arrays sorting


【解决方案1】:

您尚未在 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());

        }
    }
[...]

【讨论】:

  • 谢谢,但很遗憾,没有任何影响。
  • 是你的 print_r($times);显示正确的时间顺序?我问,因为你有另一个 foreach 循环,它遍历 $titles 并且你的函数的返回值返回 $grouped ,它是从titles循环创建的?
  • 是的,print_r($times) 正在按要求的顺序打印。就好像它在改变之前循环遍历数组一样。
猜你喜欢
  • 1970-01-01
  • 2016-08-10
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
  • 2018-04-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多