Jump to content

Recommended Posts

I need to sort the following array, first by score then by name. I am just starting to learn PHP and everything worked just fine until this. Can anyone help me?

$scores[0]['name'] = 'Michael';
$scores[0]['score'] = 13;
$scores[1]['name'] = 'Fred';
$scores[1]['score'] = 15;
$scores[2]['name'] = 'Mary';
$scores[2]['score'] = 19;

/Max
Link to comment
https://forums.phpfreaks.com/topic/10132-sort-multidimensional-array/
Share on other sites

try

[code]$scores[0]['name'] = 'Michael';
$scores[0]['score'] = 19;
$scores[1]['name'] = 'Fred';
$scores[1]['score'] = 15;
$scores[2]['name'] = 'Mary';
$scores[2]['score'] = 19;

function score_name_sort($a, $b) {
    if ($a['score'] == $b['score']) {
        return strcmp($a['name'], $b['name']);
    }
    return $a['score'] < $b['score'] ? -1 : 1;
}

usort ($scores, 'score_name_sort');

// check result
echo '<pre>', print_r($scores, true), '</pre>';[/code]
I had been working on this for days but couldn't make it work.
But your usort solution worked like a clock and solved everything.
A million thanks!!!!


About the sort($scores); function:
Is there any way to change the key by which it sorts?

Again thank you so much for your help!

/Max



nope, not that i've been able to determine. the way the sort function works is it sorts the first array sets first and then after that it looks at the 2nd array, etc.. so you would think since it does look at more than one anyways, there would be a way to do like a sort($array, $level) or something built in, but.. nope, not that i have been able to find. You gotta do a traditional sorting method like bubble sort or something, like how barand did.
IF the scores and name keys had been in the right order, eg


[code]$scores = array (
    array (
        'score' =>19,
        'name' => 'Michael'
        ),
    array (
        'score' =>15,
        'name' => 'Fred'
        ),
    array (
        'score' =>19,
        'name' => 'Mary'
        )
);[/code]

then you could have used this to sort by score then name

[code]array_multisort($scores);

echo '<pre>', print_r($scores, true), '</pre>';[/code]
?>
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.