How can I sort this array of objects by one of its fields, like name
or count
?
Array
(
[0] => stdClass Object
(
Thanks for the inspirations, I also had to add an external $translator parameter
usort($listable_products, function($a, $b) {
global $translator;
return strcmp($a->getFullTitle($translator), $b->getFullTitle($translator));
});
This is what I have for a utility class
class Util
{
public static function sortArrayByName(&$arrayToSort, $meta) {
usort($arrayToSort, function($a, $b) use ($meta) {
return strcmp($a[$meta], $b[$meta]);
});
}
}
Call it:
Util::sortArrayByName($array, "array_property_name");
usort($array, 'my_sort_function');
var_dump($array);
function my_sort_function($a, $b)
{
return $a->name < $b->name;
}
The same code will be with the count
field.
More details about usort
: http://ru2.php.net/usort
Btw, where did you get that array from? I hope that not from database?
You can use usort
, like this:
usort($array,function($first,$second){
return strcmp($first->name, $second->name);
});
A simple alternative that allows you to determine dynamically the field on which the sorting is based:
$order_by = 'name';
usort($your_data, function ($a, $b) use ($order_by)
{
return strcmp($a->{$order_by}, $b->{$order_by});
});
This is based on the Closure class, which allows anonymous functions. It is available since PHP 5.3.
If you need local based string comparison, you can use strcoll instead of strcmp
.
Remeber to first use setlocale with LC_COLLATE
to set locale information if needed.
usort($your_data,function($a,$b){
setlocale (LC_COLLATE, 'pl_PL.UTF-8'); // Example of Polish language collation
return strcoll($a->name,$b->name);
});