I\'ve read what I\'ve found on Stackoverflow and am still unclear on this.
I have an array of SimpleXML objects something like this:
array(2) {
[0]
Here's another example of using usort(). This one allows you to specify the object variable and the sort direction:
function sort_obj_arr(& $arr, $sort_field, $sort_direction)
{
$sort_func = function($obj_1, $obj_2) use ($sort_field, $sort_direction)
{
if ($sort_direction == SORT_ASC) {
return strnatcasecmp($obj_1->$sort_field, $obj_2->$sort_field);
} else {
return strnatcasecmp($obj_2->$sort_field, $obj_1->$sort_field);
}
};
usort($arr, $sort_func);
}
Test code;
class TestClass
{
public $name;
public $age;
public function __construct($name, $age)
{
$this->name = $name;
$this->age = $age;
}
}
$test[] = new TestClass('Tom', 28);
$test[] = new TestClass('Mary', 48);
$test[] = new TestClass('Beth', 38);
$test[] = new TestClass('Cindy', 18);
$test[] = new TestClass('Sid', 58);
$test[] = new TestClass('Mandy', 8);
$field = 'age';
$direction = SORT_DESC;
sort_obj_arr($test, $field, $direction);
echo '';
print_r($test);
echo '
';