PHP 使用子数组值按字母顺序排列数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10484607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP sort array alphabetically using a subarray value
提问by user6
Possible Duplicate:
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
可能的重复:
如何在 PHP 中对数组和数据进行排序?
如何在 php 中对多维数组进行
排序PHP PHP 按子数组值排序数组 PHP 按值
排序多维数组
My array looks like:
我的数组看起来像:
Array(
[0] => Array(
[name] => Bill
[age] => 15
),
[1] => Array(
[name] => Nina
[age] => 21
),
[2] => Array(
[name] => Peter
[age] => 17
)
);
I would like to sort them in alphabetic order based on their name. I saw PHP Sort Array By SubArray Valuebut it didn't help much. Any ideas how to do this?
我想根据他们的名字按字母顺序对它们进行排序。我看到PHP Sort Array By SubArray Value但它没有多大帮助。任何想法如何做到这一点?
回答by Marian Zburlea
Here is your answer and it works 100%, I've tested it.
这是你的答案,它 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);
回答by ccKep
usortis your friend:
usort是你的朋友:
function cmp($a, $b)
{
return strcmp($a["name"], $b["name"]);
}
usort($array, "cmp");

