开发者

array_multisort to sort several arrays

开发者 https://www.devze.com 2022-12-14 23:38 出处:网络
I\'ve searched for this but can\'t seem to find the exact answer. I want to use array_multisort to simultanously sort 3 arrays based on numeric values in 3 of the arrays. Basically I want to make a \"

I've searched for this but can't seem to find the exact answer. I want to use array_multisort to simultanously sort 3 arrays based on numeric values in 3 of the arrays. Basically I want to make a "standings" table similar to what you'd see for NFL/NHL standings etc. I have 3 arrays, tempIDs (string), tempWins (numeric), tempWinPercentage (numeric). I need all 3 to be sorted at the same time based first on wins, and then if there is a tie, win percentage.

I can't seem to get array_multisort to work with more than just 2 arrays, so maybe I'm misunderstanding the terminology when the开发者_StackOverflowy say that it can work with "several" arrays. Thank you!


You should have a data array like this:

$data = array(
    0 => array(
        'tempIDs' => 'something',
        'tempWins' => 10,
        'tempWinPercentage' => 50,
    ),
    1 => array(
        'tempIDs' => 'something else',
        'tempWins' => 10,
        'tempWinPercentage' => 60,
    ),
    3 => array(
        'tempIDs' => 'something more',
        'tempWins' => 20,
        'tempWinPercentage' => 50,
    ),
);

Then sort this array using usort($data, 'my_sort_cb')

Your callback method should first compare tempWins, and if they are equal, compare tempWinPercentages:

function my_sort_cb($a, $b) {
    if ($a['tempWins'] > $b['tempWins']) return 1;
    if ($a['tempWins'] < $b['tempWins']) return -1;

    if ($a['tempWinPercentage'] > $b['tempWinPercentage']) return 1;
    if ($a['tempWinPercentage'] < $b['tempWinPercentage']) return -1;
    return 0;
}

(this can be made shorter)


I can't seem to get array_multisort to work with more than just 2 arrays, so maybe I'm misunderstanding the terminology when they say that it can work with "several" arrays. Thank you!

I think they mean it can be used for sorting more than two arrays, but the other arrays will be sorted basing on the first one.

In example, executing this code

$a1 = array(12, 23, 34, 45, 45, 34);
$a2 = array(234, 56, 243, 456, 34, 346);
$a3 = array(654, 56, 8, 12, 56, 90);

array_multisort($a1, $a2, $a3);

you will get the arrays sorted as if the would have been defined as

$a1 = array(12, 23, 34, 34, 45, 45);
$a3 = array(654, 56, 8, 90, 56, 12);
0

精彩评论

暂无评论...
验证码 换一张
取 消