Laravel Sort Collection按动态ID数组

时间:2016-07-25 18:08:50

标签: php laravel laravel-5 eloquent laravel-5.2

我有以下......

$people = array(5, 2, 9, 6, 11);

$people_collection = People::find($people);

但是当我转储并死掉$people_collection时,ID ASC会对该集合进行排序,如何按照与$people数组相同的顺序保留集合?

1 个答案:

答案 0 :(得分:6)

Collections有一个sortBy函数,它接受一个自定义回调:

$people_collection = People::find($people)
   ->sortBy(function($person, $key) use($people) {
         return array_search($person->id, $people);
      });

请参阅the docs