Sort multidimensional array with minimum loop in PHP
How to sort following array with PHP based on its name
's prefix number and produce the output as
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_tax开发者_C百科onomy_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 ) )
Tried using
sort($array,SORT_NUMERIC);
foreach ( $array as $single ) {
echo $single->name;
}
but display the output as
4-Apple
2-Capico
10-Zebra
1-First
usort($array, function($a, $b)
{
return strnatcasecmp($a->name, $b->name);
});`
To sort numerically:
usort($data, function($a, $b) { return $a->name - $b->name; });
From PHP 5.3, you can use usort()
with an anonymous function. On older versions, you can use a normal compare function as illustrated in the manual.
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;
});
Sort order will be fine because your name
strings start with numbers, so PHP will parse these variables as numbers.
UPDATE: Added integer casting as suggested by @binaryLV, and also solved the 1-foo and 1-bar
problem mentioned by @konforce (with strcmp()
).
精彩评论