PHP: I have an associative array (int => object), I want to sort it

class DownTime {
    public $total, $longest, $count;
}

I have an associative array (the key is id, the value is a DownTime object).
I want to sort it according to the total amount. I read PHP: Array sorting and some other stackoverflow questions.

I understand that uasortwill work just fine. However, as an OOP approach, I would prefer to define a special function (for example, a definition operator<()in C ++ or an implementation Comparable.compareTo()in Java) inside the DownTime class, rather than passing a function when calling some sorting function.

+3
source share
2 answers

- , Iterator .

ArrayObject sort:

class MyArrayObject extends ArrayObject {
    public function natsort() {
        $this->uasort(function($a, $b) {
            return $a->total > $b->total ? 1 : -1;
        });
    }
}

$arrayObject = new MyArrayObject($array);
$arrayObject->natsort();

foreach ($arrayObject as $value) {
    //sorted values
}

, :

$array = $arrayObject->getArrayCopy();

, , / .

...

+1

compare() DownTime:

class DownTime {
    public $total, $longest, $count;
    public static function compare(DownTime $a, DownTime $b) {
        // compare $a and $b here, and return -1, 0, 1
    }
}

uasort :

uasort($array, 'DownTime::compare')

PHP "" , useland:

interface Comparable {
    function compareTo($a);
}

// a generic compare function
function compare($a, $b) {
    if ($a instanceof Comparable) return $a->compareTo($b);
    if ($a < $b) return -1;
    if ($a > $b) return 1;
    return 0;
}

// now you can sort without knowing anything about what the array contains:
uasort($array, 'compare');

ArrayObject:

class SortableArrayObject extends ArrayObject
{
    function asort() {
        return $this->uasort('compare'); // you can even make compare() a member of
                                         // SortableArrayObject and use 
                                         // $this->uasort(array($this,'compare'))
    }
}

$arrayObject->asort();

, .

+5

Source: https://habr.com/ru/post/1786685/


All Articles