简体   繁体   English

按数组中包含的最高编号随机播放

[英]Shuffle by highest number contained with in an array

This is trapped inside a PHP foreach where there are multiple results being fetched. 这被困在一个PHP foreach内部,在那里有多个结果被提取。

$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. 然后,我想根据'perc'中包含的值以降序对$frontpage进行排序,所有值都是数字。 How do I do that? 我怎么做?

Have you tried to use uasort() ? 您是否尝试过使用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 这里有很多关于如何使用usort的示例: 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. 我编写了一个简单的测试示例,假设数组中的“ perc”键始终是第一个。

<?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);
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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