このような名前のコレクションがあるとします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);
});
}
config( 'settings.data_grids')と$ categoryの違いにより、おそらく応答していません。したがって、次のようにコードを編集します
次の3行をコードに追加してください。
$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
例えば:
$categories = Category::select('*')->get(); //for example
$array = [
[
"pos" => "0",
"col" => "1",
"row" => "1",
"size_x" => "2",
"size_y" => "1",
"cat_id" => 1,
],
[
"pos" => "0",
"col" => "1",
"row" => "2",
"size_x" => "2",
"size_y" => "1",
"cat_id" => 10,
]
];
$grids = collect($array);
if ($grids->isNotEmpty()) {
$grids_arr = $grids->pluck("cat_id")->toArray();
$grids_arr = array_map('intval', $grids_arr);
//Please add these three lines to your code
$catIds = $categories->pluck('cat_id')->toArray();
$diff = array_diff($catIds, $grids_arr);
$grids_arr = array_merge($grids_arr, $diff);
//-----
$sorted = $categories->sortBy(function ($model) use ($grids_arr) {
return array_search($model->cat_id, $grids_arr);
});
return $sorted->values()->all();
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加