Skip to content

atkaye/PHP-Array-Sorter

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

PHP Array Sorter

Super simple sorting of arrays in PHP

Build Status

Features

Apply multiple ordering rules (similar to MySQL)

$input = array(
    array(
        'name'  => 'John',
        'age'   => 30
    ),
    array(
        'name'  => 'Jack',
        'age'   => 32
    ),
    array(
        'name'  => 'James',
        'age'   => 30
    ),  
);

// Sort by "age" (ascending) first, then "name" (descending)
$output = ArraySorter::create($input)
            ->addRule('age')
            ->addRule('name', SORT_DESC)
            ->sort();
            
// $output => John, James, Jack

Case-insensitve sorting (PHP 5.4)

$input = array(
    array(
        'name'  => 'john',
        'age'   => 30
    ),
    array(
        'name'  => 'Jack',
        'age'   => 32
    ),
    array(
        'name'  => 'James',
        'age'   => 30
    ),  
);

// Sort by "age" (ascending) then "name" (case insensitive, descending)
$output = ArraySorter::create($input)
            ->addRule('age')
            ->addRule('name', SORT_DESC, SORT_STRING | SORT_FLAG_CASE)
            ->sort();
            
// $output => jonn, James, Jack

Sort using a closure or class method

$input = array(
    new DateTime('2013-01-01'),
    new DateTime('2014-01-01'),
    new DateTime('2012-01-01')
);

// Sort by dates by seconds since epoch (ascending)
$output = ArraySorter::create($input)->addRule(function($date) {
    // Return the value to be sorted by
    return $date->format('U');
})->sort();

// $output => 2012-01-01, 2013-01-01, 2014-01-01

Sort without modifying array keys

$input = array(
    'John'  => 31,
    'Jack'  => 32,
    'James' => 30
);
// Sort names by value ASC without modifying keys
$output = ArraySorter::create($input)->sort(TRUE);

// $output => James, John, Jack

Coming Soon

  • Pass array key to closure function
  • Support for pass-by-reference
  • Performance improvements
  • Case-insensitive sorting for PHP 5.3
  • Add Documentation for SORT_NATURAL
  • PHPUnit tests

Current Version

0.1.1

License

MIT