0

Is there any laravel collection methold that i dont know of, which would allow me to sort an array based on the number of elements on the sub array?

Illuminate\Support\Collection {#1143 ▼
  #items: array:7 [▼
    "A" => Illuminate\Support\Collection {#21181 ▼
      #items: array:10 [▶]
    }
    "B" => Illuminate\Support\Collection {#21182 ▼
      #items: array:8 [▶]
    }
    "C" => Illuminate\Support\Collection {#21183 ▼
      #items: array:9 [▶]
    }
    "D" => Illuminate\Support\Collection {#21184 ▼
      #items: array:5 [▶]
    }
    "E" => Illuminate\Support\Collection {#21185 ▼
      #items: array:2 [▶]
    }
    "F" => Illuminate\Support\Collection {#21186 ▼
      #items: array:4 [▶]
    }
    "G" => Illuminate\Support\Collection {#21187 ▼
      #items: array:15 [▶]
    }
  ]
}

I could do something like THIS using usort() but I was just wondering if there exists any method within laravel collections, which I yet dont know or may be I am not able to locate it within Laravel Collections.

2

2 Answers 2

2

I don't know if anyone is going to stumble into similar problem, I found a way around it as mentioned in the documentation

I still don't know if this is the perfect way of doing it, but it did the trick for me. I am just posting it such that it might help someone a lot of headache and time.

I would still love to hear other answers and comments on the alternative ways of doing it.

$sorted = $mostWatchedVideosThisWeek->sortByDesc(function ($stats, $key) {
     return count($stats);
});
Sign up to request clarification or add additional context in comments.

1 Comment

That would be the preferred way to do this in the Laravel way. An alternative way may be applied if that collection of collections is generated from a database query, where you could apply sorting at query level instead of php level.
0

if you searching for usort(), Laravel https://laravel.com/docs/5.8/collections#method-sort work same like usort()

eg:

 $full_sorted = $collection_data->sort(function($a ,$b) { //$a first element ,$b second element
                if ((count($a) > count($b))) {
                        return -1; 
                }else{
                   return 1;
                }
            })->values();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.