ahmadbadpey's avatar

sort a collection according to an array of IDs in Laravel

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);
                });
            }

Note that it is possible count of array elements was not equal elements of collection.

0 likes
2 replies
mvd's avatar

Hi Ahmadbadpey,

You can sort the collection on the cat_id with something like this

  $x = $collection->toArray();
  usort($x, function($v1, $v2) {
    return strcmp($v1['cat_id'], $v2['cat_id']);
  });

  dd($x);
Drfraker's avatar

You can use collection methods for this:

$ids = collect([11,10,1]);

$sorted = $ids->map(function($id) use($categories) {
    return $categories->where('cat_id', $id)->first();
});

1 like

Please or to participate in this conversation.