我有这个数组,例如:
$exampleArray = array (
array( 'Name' => 'Opony', 'Kod' =>'OPO', 'Price' => 100 ),
array( 'Kod' =>'OLE', 'Name' => 'Olej', 'Price' => 20 ),
array( 'Kod' =>'ABC', 'Price' => 20, 'Name' => 'abcdefg' )
)
子数组中的键是随机顺序的。我想按键对子数组进行排序:
Array ( [0] => Array ( [Kod] => OPO [Name] => Opony [Price] => 100 ) [1] => Array ( [Kod] => OLE [Name] => Olej [Price] => 20 )
我试试这个:
function compr($x,$y){
if($x == $y)
return 0;
elseif($x>$y)
return 1;
elseif($x<$y)
return-1;
}
uksort($exampleArray, 'compr');
print_r($exampleArray);
但是这段代码并没有给我预期的结果,有什么不对,我该如何解决呢?
答案 0 :(得分:2)
这应该适合你:
只需循环遍历所有内部数组by reference
,然后只需使用uksort()
和strcasecmp()
按键对内部数组进行排序。
foreach($exampleArray as &$v) {
uksort($v, function($a, $b){
return strcasecmp($a, $b);
});
}
unset($v); //So if you use $v later it doesn't change the last element of the array by reference
输出:
Array
(
[0] => Array
(
[Kod] => OPO
[Name] => Opony
[Price] => 100
)
//...
[2] => Array
(
[Kod] => ABC
[Name] => abcdefg
[Price] => 20
)
)