PHP排序多维数组usort()
问题描述:
我有下面的数组,并想按字母顺序按名称排序。我对如何使用usort()函数对此感到有些困惑,因为我无法使用它,还是有更好的函数使用?
I have the below array and want to order it alphbetically by "Name". I am a little confused on how to use the usort() function for this as what I have does not work, or is there a better function to use?
Array (
[0] => SimpleXMLElement Object
(
[id] => 1118809
[Name] => Laptop
[parentID] => 0
[sequence] => 4
[visible] => 1
)
[1] => SimpleXMLElement Object
(
[id] => 1109785
[Name] => Special Offers
[parentID] => 0
[sequence] => 0
[visible] => 1
)
[2] => SimpleXMLElement Object
(
[id] => 1118805
[Name] => Printers
[parentID] => 0
[sequence] => 12
[visible] => 0
)
[3] => SimpleXMLElement Object
(
[id] => 1092140
[Name] => USB
[parentID] => 0
[sequence] => 14
[visible] => 1
) )
function sort_cats_by_name($a, $b) {
return $a->Name - $b->Name;
}
usort($subcats, 'sort_cats_by_name');
答
哎呀,减去字符串似乎是一种奇怪的方法做字符串比较,就行不通了!
Ouch, substracting strings seems to be a strange way to do string comparisons , it could not work!!
这应该更好。
function sort_cats_by_name($a, $b) {
return strcmp($a->Name,$b->Name);
}