簡體   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