我遇到排序多维数组的问题。
print_r($myarray);
正在提供以下输出:
Array
(
[0] => Array
(
[ID] => 10
[Code] => 12-111
[Name] => putup1
)
[1] => Array
(
[ID] => 11
[Code] => 12-21
[Name] => putup2
)
[2] => Array
(
[ID] => 12
[Code] => 12-1
[Name] => putup2
)
)
我从此链接中获取了引用:Sort MultiDimensional Array并使用列Code
进行排序。它给了我这样的输出:
Array
(
[0] => Array
(
[ID] => 10
[Code] => 12-1
[Name] => putup1
)
[1] => Array
(
[ID] => 12
[Code] => 12-111
[Name] => putup2
)
[2] => Array
(
[ID] => 11
[Code] => 12-21
[Name] => putup2
)
)
我希望输出如下:
Array
(
[0] => Array
(
[ID] => 10
[Code] => 12-1
[Name] => putup1
)
[2] => Array
(
[ID] => 11
[Code] => 12-21
[Name] => putup2
)
[1] => Array
(
[ID] => 12
[Code] => 12-111
[Name] => putup2
)
)
有可能吗?请建议我...... 谢谢:))
答案 0 :(得分:1)
您目前正在对代码进行排序,但是作为文本而不是数字。要根据需要对其进行排序,您必须编写一个比较函数,指示一个代码是否大于另一个代码:
function sortByCode($a, $b) {
$aParts = explode('-', $a['Code']);
$bParts = explode('-', $b['Code']);
for ($i = 0; $i < count($aParts); $i++) {
if ($aParts[$i] < $bParts[$i]) {
return -1;
} else if ($aParts[$i] > $bParts[$i]) {
return 1;
}
}
return 0;
}
usort($myArray, 'sortByCode');