如何使用PHP基于name
的前缀编号对以下数组进行排序,并将输出生成为
1-First
2-Capico
4-Apple
10-Zebra
$array = Array ( [0] => stdClass Object ( [term_id] => 6 [name] => 1-First [slug] => aaa-a [term_group] => 0 [term_taxonomy_id] => 6 [taxonomy] => category [description] => [parent] => 4 [count] => 2 [cat_ID] => 6 [category_count] => 2 [category_description] => [cat_name] => 1-First [category_nicename] => aaa-a [category_parent] => 4 )
[1] => stdClass Object ( [term_id] => 9 [name] => 10-Zebra [slug] => aaa-f [term_group] => 0 [term_taxonomy_id] => 9 [taxonomy] => category [description] => [parent] => 4 [count] => 1 [cat_ID] => 9 [category_count] => 1 [category_description] => [cat_name] => 10-Zebra [category_nicename] => aaa-f [category_parent] => 4 )
[2] => stdClass Object ( [term_id] => 8 [name] => 2-Capico [slug] => aaa-c [term_group] => 0 [term_taxonomy_id] => 8 [taxonomy] => category [description] => [parent] => 4 [count] => 1 [cat_ID] => 8 [category_count] => 1 [category_description] => [cat_name] => 2-Capico [category_nicename] => aaa-c [category_parent] => 4 )
[3] => stdClass Object ( [term_id] => 7 [name] => 4-Apple [slug] => aaa-b [term_group] => 0 [term_taxonomy_id] => 7 [taxonomy] => category [description] => [parent] => 4 [count] => 1 [cat_ID] => 7 [category_count] => 1 [category_description] => [cat_name] => 4-Apple [category_nicename] => aaa-b [category_parent] => 4 ) )
尝试使用
sort($array,SORT_NUMERIC);
foreach ( $array as $single ) {
echo $single->name;
}
但显示输出为
4-Apple
2-Capico
10-Zebra
1-First
答案 0 :(得分:3)
从PHP 5.3开始,您可以将usort()
与anonymous function一起使用。在旧版本中,您可以使用常规比较功能,如手册中所示。
usort($array, function ($a, $b) {
//saving values converted to integer
$intAname=(int) $a->name;
$intBname=(int) $b->name;
//if they are equal, do string comparison
if ($intAname == $intBname) {
return strcmp($a->name, $b->name);
}
return ($intAname < $intBname) ? -1 : 1;
});
排序顺序很好,因为您的name
字符串以数字开头,因此PHP会parse these variables as numbers。
UPDATE:按@binaryLV的建议添加了整数转换,并解决了@konforce(1-foo and 1-bar
)提到的strcmp()
问题。
答案 1 :(得分:3)
usort($array, function($a, $b)
{
return strnatcasecmp($a->name, $b->name);
});`
答案 2 :(得分:3)
以数字方式排序:
usort($data, function($a, $b) { return $a->name - $b->name; });