PHP:在循环中使用Usort()

时间:2018-04-05 20:40:25

标签: php function loops usort

我正在尝试对多维数组进行排序。

我的数组中有以下结构:

array
(
    [1] => stdClass Object
        (
            [events] => Array
                (
                    [0] => stdClass Object
                        (
                            [id] => 1
                            [task] => task1
                            [date_task] => 2018-04-02
                            [start] => 8
                            [end] => 10
                        )

                    [1] => stdClass Object
                        (
                            [id] => 7
                            [task] => task 32
                            [date_task] => 2018-04-02
                            [start] => 10
                            [end] => 12
                        )
                )
        )
    [2] => stdClass Object
        (
           [events] => Array
                (
                    [0] => stdClass Object
                        (
                            [id] => 4
                            [task] => task4
                            [date_task] => 2018-04-06
                            [start] => 11
                            [end] => 15
                        )
                    [1] => stdClass Object
                        (
                            [id] => 5
                            [task] => task5
                            [date_task] => 2018-04-06
                            [start] => 8
                            [end] => 10
                        )
                )
        )
)

如果我尝试在循环FOR或FOREACH中使用Usort()函数,如下所示:

for ($i = 1; $i <= count($MyArray); $i++) {
         usort($MyArray[$i]->events, function($a, $b) {
         return $b->start <=> $a->start;
     });
    }

我收到此错误:

  

usort()期望参数1为数组,字符串为

我怎么能解决这个问题?

1 个答案:

答案 0 :(得分:2)

1.使用foreach()而不是for()。 (因为它照顾索引本身)。

2.使用passing by reference mechanism

如下所示: -

foreach ($MyArray as &$MyArr) {
  foreach ($MyArr as &$MyAr) {
    if (is_array($MyAr)){
       usort($MyAr, function($a, $b) {
          return ($b->start <= $a->start) ? 1 : -1;
       });
    }
  }
}

print_r($MyArray);

输出: - https://eval.in/984958