AlexHeuman
AlexHeuman

Reputation: 1006

Sorting array of objects by function in PHP

Let's say I have an object called ACCOUNT like:

class ACCOUNT
{
private $contact;
public function getContact();
}

and another object CONTACT:

class CONTACT
{
   private $lastName;
   public function getLastName()
   {
      return $this->lastName;
   }
}

Then I create an array of these objects $accountArray = ACCOUNT::get(); How can I sort this array alphabetically by something like $account->getContact()->getLastName();?

What I've tried:

class Account
{
    private $contact;
    public function getContact();

    public static function cmp($a,$b)
    {
       $al = strtolower($a->getContact()->getLastName());
       $bl = strtolower($b->getContact()->getLastName());
       if ($al == $bl) {
       return 0;
       }
       return ($al > $bl) ? +1 : -1;
    }
    public static function sortByLastName($accountArray)
    {
       usort($moACOUNTArray, array('ACCOUNT', 'cmp'));
    }
}

But I get this error:

 Call to undefined method ACCOUNT::getContact()

Upvotes: 0

Views: 58

Answers (1)

aslawin
aslawin

Reputation: 1981

You can use usort function of PHP, like mentioned in comments. There is self-explaining example:

Try this code:

<?php

class ACCOUNT
{
    private $contact;
    public function getContact()
    {
        return $this->contact;
    }

    public function setContact($v)
    {
        $this->contact = $v;
    }
}

class CONTACT
{
    private $lastName;

    public function getLastName()
    {
        return $this->lastName;
    }

    public function setLastName($v)
    {
        $this->lastName = $v;
    }
}

//create data for testing
$c1 = new CONTACT;
$c1->setLastName('aaaa');
$a1 = new ACCOUNT;
$a1->setContact($c1);

$c2 = new CONTACT;
$c2->setLastName('zzz');
$a2 = new ACCOUNT;
$a2->setContact($c2);

$c3 = new CONTACT;
$c3->setLastName('ggg');
$a3 = new ACCOUNT;
$a3->setContact($c3);

$array = array($a1, $a2, $a3);


//making sort
function cmp($a, $b)
{
    return strcmp($a->getContact()->getLastName(), $b->getContact()->getLastName());
}

usort($array, "cmp");

//showing sort result
echo '<pre>';
print_r($array);

Result is:

Array
(
    [0] => ACCOUNT Object
        (
            [contact:ACCOUNT:private] => CONTACT Object
                (
                    [lastName:CONTACT:private] => aaaa
                )

        )

    [1] => ACCOUNT Object
        (
            [contact:ACCOUNT:private] => CONTACT Object
                (
                    [lastName:CONTACT:private] => ggg
                )

        )

    [2] => ACCOUNT Object
        (
            [contact:ACCOUNT:private] => CONTACT Object
                (
                    [lastName:CONTACT:private] => zzz
                )

        )

)

Upvotes: 1

Related Questions