-1

我有一个包含“客户”和“总计”的数据数组。(下面的例子)。它来自两个不同的数据库。

我需要一种基于 Total 字段对数组进行排序的方法,以便最大的总数位于顶部。但是到目前为止,我尝试过的每件事都导致它假设 5 大于 32 [5, 32, 25, 16, 11]

实现这一目标的最简单方法是什么?我尝试将 intval() 添加到 strcmp 函数中,但没有区别吗?

$arrayName = array();

$arrayName[] = array ('customer' => 'Customer1', 'Total' => 25);
$arrayName[] = array ('customer' => 'Customer2', 'Total' => 16);
$arrayName[] = array ('customer' => 'Customer3', 'Total' => 32);
$arrayName[] = array ('customer' => 'Customer4', 'Total' => 5);
$arrayName[] = array ('customer' => 'Customer5', 'Total' => 11);

print_r($arrayName);
print "</br>";

//Sort the Arrray by Total
function arrSort1($b, $a)
{
    return strcmp($a['Total']), $b['Total']);
};

usort($arrayName, "arrSort1");

print_r($arrayName);
4

1 回答 1

1

您正在按字符串进行比较,但您确实想按数值进行比较。尝试:

function arrSort1($b, $a)
{
    if ($a['Total'] > $b['Total']) {
        return 1;
    } else if ($a['Total'] < $b['Total']) {
        return -1;
    }
    return 0;
}

排序后的数组将如下所示:

Array
(
    [0] => Array
        (
            [customer] => Customer3
            [Total] => 32
        )

    [1] => Array
        (
            [customer] => Customer1
            [Total] => 25
        )

    [2] => Array
        (
            [customer] => Customer2
            [Total] => 16
        )

    [3] => Array
        (
            [customer] => Customer5
            [Total] => 11
        )

    [4] => Array
        (
            [customer] => Customer4
            [Total] => 5
        )

)
于 2013-10-25T15:33:04.147 回答