你还在为如何使用PHP排序字母+数字的数组而烦恼吗?
今天有个小伙伴在群里问:
如何将一个key为字母+数字的数组按升序排序呢?
举个例子:
$test = [ 'n1' => 22423, 'n10' => 22423, 'n2' => 'werwerw', 'n3' => 22423, 'n4' => 22423, 'n5' => 22423, 'n21' => 22423, 'n11' => 22423, ];
希望将它排序成这样子:
$test = [ 'n1' => 22423, 'n2' => 'werwerw', 'n3' => 22423, 'n4' => 22423, 'n5' => 22423, 'n10' => 22423, 'n11' => 22423, 'n21' => 22423, ]
PHP数组函数帮到你
$test = [ 'n1' => 22423, 'n10' => 22423, 'n2' => 'werwerw', 'n3' => 22423, 'n4' => 22423, 'n5' => 22423, 'n21' => 22423, 'n11' => 22423, ]; ksort($test, SORT_NATURAL); var_dump($test);
得到的结果:
array (size=8) 'n1' => int 22423 'n2' => string 'werwerw' (length=7) 'n3' => int 22423 'n4' => int 22423 'n5' => int 22423 'n10' => int 22423 'n11' => int 22423 'n21' => int 22423
https://www.cnblogs.com/ailhc/p/7594585.html
另外还有常用的,针对二维数组进行的排序:
$countRate = array(
array(
'rate'=>1,
'name'=>'aabb'
),
array(
'rate'=>2,
'name'=>'bbcc'
)
)
array_multisort(array_column($countRate, 'rate'), SORT_DESC, $countRate, array_column($countRate, 'dep'), SORT_DESC, $countRate);