可能重复:
How can I sort arrays and data in PHP?
How do I sort a multidimensional array in php
PHP Sort Array By SubArray Value
PHP sort multidimensional array by value
我的数组看起来像:
Array(
[0] => Array(
[name] => Bill
[age] => 15
),
[1] => Array(
[name] => Nina
[age] => 21
),
[2] => Array(
[name] => Peter
[age] => 17
)
);
我想根据他们的名字按字母顺序对它们进行排序。 我看到了PHP Sort Array By SubArray Value,但没有多大帮助。 任何想法如何做到这一点?
答案 0 :(得分:131)
这是你的答案,它100%有效,我已经测试过了。
<?php
$a = Array(
1 => Array(
'name' => 'Peter',
'age' => 17
),
0 => Array(
'name' => 'Nina',
'age' => 21
),
2 => Array(
'name' => 'Bill',
'age' => 15
),
);
function compareByName($a, $b) {
return strcmp($a["name"], $b["name"]);
}
usort($a, 'compareByName');
/* The next line is used for debugging, comment or delete it after testing */
print_r($a);
答案 1 :(得分:14)
usort
是你的朋友:
function cmp($a, $b)
{
return strcmp($a["name"], $b["name"]);
}
usort($array, "cmp");