简体   繁体   中英

Shuffle by highest number contained with in an array

This is trapped inside a PHP foreach where there are multiple results being fetched.

$frontpage[] = array(
    'perc' => $percentage, 
    'id' => $result->ID
);

I then want to sort $frontpage in descending order according to the values contained in 'perc', all of which are numbers. How do I do that?

Have you tried to use uasort() ? It's a function with which you define a callback function that compares certain values.

function customCompare($a, $b)
{
    if ($a['perc'] == $b['perc']) {
        return 0;
    }
    return ($a['perc'] < $b['perc']) ? -1 : 1;
}

uasort($frontpage, 'customCompare');
$frontpage = array_reverse($frontpage); // for descending order

See it in action here.

There are loads of examples on how to use usort here: http://php.net/manual/en/function.usort.php

I wrote a simple test example assuming that the 'perc' key in the array is always the first one.

<?php

function percentCompare($a, $b)
{
        if ($a == $b)
                return 0;

        //we want it decending
        return ($a > $b) ? -1 : +1;
}

$frontpage[] = array();

//Fill the array with some random values for test
for ($i = 0; $i < 100; $i++)
{
        $frontpage[$i] = array(
                'perc' => rand($i, 100),
                'id' => $i
                );
}

//Sort the array
usort($frontpage, 'percentCompare');

print_r($frontpage);
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM