我有一系列数据,包括'客户'和'总计'。 (以下示例)。它来自两个不同的数据库。
我需要一种基于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);
答案 0 :(得分: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
)
)