Suppose I have a collection like this named 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"
]
]
}
On the other hand there is an array of IDs like this :
[11,10,1]
Now I want to sort element of that collection based on their cat_id
index as sorted in an array. means I want result array to be like this :
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"
]
]
}
I used below codes but does not work properly:
$grids_arr = [11,10,1];
$categories = $categories->sortBy(function ($model) use ($grids_arr) {
return array_search($model->cat_id, $grids_arr);
});
Update :
This is my completed Code I'm using:
$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);
});
}