繁体   English   中英

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

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

这被困在一个PHP foreach内部,在那里有多个结果被提取。

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

然后,我想根据'perc'中包含的值以降序对$frontpage进行排序,所有值都是数字。 我怎么做?

您是否尝试过使用uasort() 它是一个函数,您可以使用该函数定义比较某些值的回调函数。

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

在这里查看实际操作。

这里有很多关于如何使用usort的示例: http : //php.net/manual/en/function.usort.php

我编写了一个简单的测试示例,假设数组中的“ 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