How to sort array of classes based on the value of property

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Moti.Ba@gmail.com

    How to sort array of classes based on the value of property

    Hello,

    I have a class like this one

    Class foo
    {
    public $sum;
    }

    And I have an array of instances based on this class. When I use
    ksort() the array is sorted by key, next I want to sort it by the $sum
    property.

    How can I do it?

  • ZeldorBlat

    #2
    Re: How to sort array of classes based on the value of property


    Moti.Ba@gmail.c om wrote:
    Hello,
    >
    I have a class like this one
    >
    Class foo
    {
    public $sum;
    }
    >
    And I have an array of instances based on this class. When I use
    ksort() the array is sorted by key, next I want to sort it by the $sum
    property.
    >
    How can I do it?
    Try usort():
    <http://www.php.net/usort>

    Something like this should work:

    function cmpFoo($a, $b)
    {
    if ($a->sum == $b->sum)
    return 0;

    return ($a->sum < $b->sum) ? -1 : 1;
    }

    usort($arr, "cmpFoo"); //$arr is the array of objects

    Comment

    Working...