lithium\util\Collection::sort PHP Method

sort() public method

Sorts the objects in the collection.
public sort ( string | callable $sorter = 'sort', array $options = [] ) : Collection
$sorter string | callable The sorter for the data. Either a callable to use as the sort function or a string with the name of a well-known sort function like `'natsort'` or a compare function like `'strcmp'`. Defaults to `'sort'`.
$options array Reserved for future use.
return Collection Returns itself.
    public function sort($sorter = 'sort', array $options = array())
    {
        if (is_string($sorter) && strpos($sorter, 'sort') !== false && is_callable($sorter)) {
            call_user_func_array($sorter, array(&$this->_data));
        } elseif (is_callable($sorter)) {
            usort($this->_data, $sorter);
        }
        return $this;
    }

Usage Example

Beispiel #1
0
 /**
  * Tests that the Collection::sort method works appropriately.
  */
 public function testCollectionSort()
 {
     $collection = new Collection(array('data' => array(5, 3, 4, 1, 2)));
     $collection->sort();
     $expected = array(1, 2, 3, 4, 5);
     $this->assertEqual($expected, $collection->to('array'));
     $collection = new Collection(array('data' => array('alan', 'dave', 'betsy', 'carl')));
     $expected = array('alan', 'betsy', 'carl', 'dave');
     $this->assertEqual($expected, $collection->sort()->to('array'));
     $collection = new Collection(array('data' => array('Alan', 'Dave', 'betsy', 'carl')));
     $expected = array('Alan', 'betsy', 'carl', 'Dave');
     $this->assertEqual($expected, $collection->sort('strcasecmp')->to('array'));
     $collection = new Collection(array('data' => array(5, 3, 4, 1, 2)));
     $collection->sort(function ($a, $b) {
         if ($a === $b) {
             return 0;
         }
         return $b > $a ? 1 : -1;
     });
     $expected = array(5, 4, 3, 2, 1);
     $this->assertEqual($expected, $collection->to('array'));
     $collection = new Collection(array('data' => array(5, 3, 4, 1, 2)));
     $result = $collection->sort('blahgah');
     $this->assertEqual($collection->to('array'), $result->to('array'));
 }
All Usage Examples Of lithium\util\Collection::sort