Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Blitzkrieg's avatar

Sorting Foreach by Another Variable

Hi,

I have a loop like this;

foreach($data['cevaplayanlar'] as $user)
                <div class="flex justify-between my-1">
                <p>{{ $user->name }}</p><p>Puan: {{ $data['quiz']->getUserScore($user->id) }}</p>
                </div>
endforeach

I have a user collection in $data['cevaplayanlar'] And I want to loop through this collection[.] For every data, I get that users ID and calculate his score with fuction getUserScore based on the ID of the quiz[.] But that function needs the ID of the user[.] So I can't use it outside of loop[.]

So there is a function that uses a function from Quiz model (getUserScore(userid)) I want to sort the data by getUserScore return value Is it possible? How can I do that?

0 likes
12 replies
CorvS's avatar
CorvS
Best Answer
Level 27

If I understand you correctly, you want to sort the users inside $data['cevaplayanlar'] by their score?

$sortedUsers = collect($data['cevaplayanlar'])->sortBy(function ($user) use ($data) {
    return $data['quiz']->getUserScore($user->id);
})
3 likes
Blitzkrieg's avatar

Kind of[.] I have a user collection in $data['cevaplayanlar'] And I want to loop through this collection[.] For every data, I get that users ID and calculate his score with fuction getUserScore based on the ID of the quiz[.] But that function needs the ID of the user[.] So I can't use it outside of loop[.] Is it too much to ask :)

CorvS's avatar

I mean you could save the score of each user for each quiz inside a database table and sort them when querying the database. That way you don't have to "loop" over them another time to sort by score.

1 like
Blitzkrieg's avatar

I want them to be dynamic[.] So if I want to change the calculation system, I don't want to edit all scores all over[.]

Tray2's avatar

Where do you get the data from?

If it's the database you should do the calculation and the sorting there.

1 like
Blitzkrieg's avatar

Yeah but it's a bit complicated[.] I have a table holding the answers (Cols; id, userid, questionid, answer)[.] And another table holding the questions (it has the id of the quiz it belongs to)[.] When I'm fetching users checking the answers questions, then checking that questions if it's quiz id is the same with specified quiz[.] And the grouping the results by userID[.] This is the way how i create collection[.] After that I make a loop in the collection, and check the users answers (from answers table), and then compare that answer with the correct answer column in questions table[.] (Hope I was clear :/)

Tray2's avatar

Not really but all of that is doable in SQL.

sr57's avatar

If you do not do the job in the db, either you have the right associative array or first you construct it

Then the easiest way to do a simple sort on an associative array is to use

asort : to sort by value

ksort : to sort by key

then you can foreach ...

and if you need to reverse key/value you can use array_flip

1 like
Blitzkrieg's avatar

I solved it by automica's answer[.] (I think he was deleted the answer).

Solution:

First, in the controller, I've put every data in array in a new array with foreach;

        $userData = [];
        foreach($data['cevaplayanlar'] as $index => $user) {
            $userData[$index]['id']= $user->id;
            $userData[$index]['name']= $user->name;
            $userData[$index]['score'] = $data['quiz']->getUserScore($user->id);
        };

and then sort it the way I want;

        $sorted = Arr::sort($userData, function($user)
        {
            return $user['score'];
        });

And sent that array to view[.] And used it in a foreach like the first one[.] And everything's perfect!

Thank you guys for your help[.] I appreciate it[.]

MichalOravec's avatar

It's exactly the same as @nimrod gave you.

$sortedUsers = collect($data['cevaplayanlar'])->sortBy(function ($user) use ($data) {
    return $data['quiz']->getUserScore($user->id);
})->toArray();
1 like
Blitzkrieg's avatar

Oh! I have tried that but faced some errors[.] Probably missed something[.] Now i checked again and worked well[.] Sorry dude[.] Thanks again!

Please or to participate in this conversation.