If I have an object as such:
class Person {
var $age;
function __construct($age) {
$this->age = $age;
}
}
and I have any array
Yes. If you implement spl ArrayObject in your person object, all the normal php array functions will work properly with it.
For that specific scenario, you can sort it using the usort() function, where you define your own function to compare the items in the array.
<?php
class Person {
var $age;
function __construct($age) {
$this->age = $age;
}
}
function personSort( $a, $b ) {
return $a->age == $b->age ? 0 : ( $a->age > $b->age ) ? 1 : -1;
}
$person1 = new Person(14);
$person2 = new Person(5);
$person3 = new Person(32);
$person4 = new Person(150);
$person5 = new Person(39);
$people = array($person1, $person2, $person3, $person4, $person5);
print_r( $people );
usort( $people, 'personSort' );
print_r( $people );
Try usort: http://www.php.net/manual/en/function.usort.php
Example:
<?php
function cmp($obja, $objb)
{
$a = $obja->sortField;
$b = $objb->sortField;
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
$a = array( /* your objects */ );
usort($a, "cmp");
?>