我想对一个php数组进行排序,其键值组合是动态的,因此很难定义一个函数并应用usort() 这是数组
Array (
[0] => Array ( [PAYE] => 43 )
[1] => Array ( [VAT] => 2 )
[2] => Array ( [NHIF] => 1 )
[3] => Array ( [NSSF] => 2 )
[4] => Array ( [MPESA] => 1 )
[5] => Array ( [EQUITEL] => 1 )
[6] => Array ( [AIRTEL] => 1 )
[7] => Array ( [CER] => 2 )
[8] => Array ( [BDD] => 4 )
[9] => Array ( [BMI] => 1 )
[10] => Array ( [TG] => 7 )
[11] => Array ( [BT] => 3 )
[12] => Array ( [EPL] => 4 )
[13] => Array ( [KPL] => 8 )
)
我想使用最右边的值对数组进行排序。结果应该是
Array (
[0] => Array ( [PAYE] => 43 )
[13] => Array ( [KPL] => 8 )
[10] => Array ( [TG] => 7 )
[8] => Array ( [BDD] => 4 )
[12] => Array ( [EPL] => 4 )
[11] => Array ( [BT] => 3 )
[7] => Array ( [CER] => 2 )
[3] => Array ( [NSSF] => 2 )
[1] => Array ( [VAT] => 2 )
[3] => Array ( [NSSF] => 2 )
[6] => Array ( [AIRTEL] => 1 )
[9] => Array ( [BMI] => 1 )
[4] => Array ( [MPESA] => 1 )
[2] => Array ( [NHIF] => 1 )
)
我应该怎么做?
答案 0 :(得分:1)
使用uasort
函数保存密钥,array_shift
使用值进行比较
uasort($array, function($i1, $i2) {
return array_shift($i2) - array_shift($i1); });
print_r($array);
答案 1 :(得分:1)
current
和// $arr is your initial array
uasort($arr, function($a, $b){ // will maintain index association
return current($b) - current($a);
});
函数可以完成这项工作:
{{1}}