根据Laravel中的ID数组对集合进行排序

时间:2018-11-15 19:57:07

标签: php laravel

假设我有一个名为categories的集合:

Collection {#447
  #items: array:3 [
    0 => array:6 [
      "pos" => "0"
      "col" => "1"
      "row" => "1"
      "size_x" => "2"
      "size_y" => "1"
      "cat_id" => "1"
    ]
    1 => array:6 [
      "pos" => "0"
      "col" => "3"
      "row" => "1"
      "size_x" => "1"
      "size_y" => "1"
      "cat_id" => "11"
    ]
    2 => array:6 [
      "pos" => "0"
      "col" => "1"
      "row" => "2"
      "size_x" => "2"
      "size_y" => "1"
      "cat_id" => "10"
    ]
]
}

另一方面,有一个ID数组:

[11,10,1]

现在,我想根据数组中的cat_id索引对该集合的元素进行排序。表示我希望结果数组像这样:

Collection {#447
  #items: array:3 [
    0 => array:6 [
      "pos" => "0"
      "col" => "3"
      "row" => "1"
      "size_x" => "1"
      "size_y" => "1"
      "cat_id" => "11"
    ]
    1 => array:6 [
      "pos" => "0"
      "col" => "1"
      "row" => "2"
      "size_x" => "2"
      "size_y" => "1"
      "cat_id" => "10"
    ]
    2 =>array:6 [
      "pos" => "0"
      "col" => "1"
      "row" => "1"
      "size_x" => "2"
      "size_y" => "1"
      "cat_id" => "1"
    ] 
]
}

我使用了以下代码,但无法正常工作:

$grids_arr  = [11,10,1];

$categories = $categories->sortBy(function ($model) use ($grids_arr) {
    return array_search($model->cat_id, $grids_arr);
});

更新:
这是我正在使用的完整代码:

        $categories = Category::isTile()->get();

        $grids = collect(config('settings.data_grids'));// This is an array of IDs
        if ($grids->isNotEmpty()) {

            $grids_arr = $grids->pluck("cat_id")->toArray();
            $grids_arr = array_map('intval', $grids_arr); //convert string array elements to integer

            $categories = $categories->sortBy(function ($catg) use ($grids_arr) {
                return array_search($catg->cat_id, $grids_arr);
            });
        }

2 个答案:

答案 0 :(得分:2)

请检查下面的代码。

$array = [
    0 => [
      "pos" => "0",
      "col" => "3",
      "row" => "1",
      "size_x" => "1",
      "size_y" => "1",
      "cat_id" => "11",
    ],
    1 => [
      "pos" => "0",
      "col" => "1",
      "row" => "2",
      "size_x" => "2",
      "size_y" => "1",
      "cat_id" => "10",

    ],
    2  => [

      "pos" => "0",
      "col" => "1",
      "row" => "1",
      "size_x" => "2",
      "size_y" => "1",
      "cat_id" => "1",
    ],
];

$array = array_reverse(array_sort($array, function ($value)
{
    return $value['cat_id'];
}));

dd($array);

希望对您有帮助。

答案 1 :(得分:2)

由于config('settings.data_grids')和$ categories之间的差异,您可能没有响应。因此,请按如下所示编辑代码

请在代码中添加以下三行:

TreeSet

例如:

$catIds = $categories->pluck('cat_id')->toArray(); //get all cat_id
$diff = array_diff($catIds, $grids_arr); // difference array from query
$grids_arr = array_merge($grids_arr , $diff); //merge difference with array