Jürgen Paul
Jürgen Paul

Reputation: 15007

Sort first level of a 2d array by a column (ascending) and preserve first level keys

For an instance you have an array:

$unsorted = array(
    'desert' => array(
        'time' => '1339902235',
        'name' => 'desert.jpg'
    ),
    'sea' => array(
        'time' => '1339900801',
        'name' => 'sea.jpg'
    ),
    'mountain' => array(
        'time' => '1339902285',
        'name' => 'mountain.jpg'
    ),
);

Would it be possible to sort the array by the value of $unsorted[$a]['time']?

Upvotes: 0

Views: 1853

Answers (4)

mickmackusa
mickmackusa

Reputation: 47874

Use modern syntax.

Call uasort() to perform a custom sort while preserving keys.

Use arrow function syntax to keep the code concise.

Use the 3-way "spaceship" operator to return the appropriate integer value. Comparing $a values on the left and $b values on the right will execute an ascending sorting direction.

Code: (Demo)

uasort(
    $unsorted,
    fn($a, $b) => $a['time'] <=> $b['time']
);
var_export($unsorted);

Upvotes: 0

trante
trante

Reputation: 33996

Note that usort doesn't preserve keys.
If you need original keys you should use uasort.

Upvotes: 0

Cfreak
Cfreak

Reputation: 19309

You can using usort. usort takes a callback as an argument. Also convert time to integers because that's what they are.

function compare($a,$b) {
     if( $a['time'] == $b['time'] ) {
         return 0;
     }

     return (intval($a['time']) < intval($b['time'])) ? -1 : 1;
}

usort( $unsorted, 'compare' );

// $unsorted is now sorted by time

Upvotes: 0

Lucas
Lucas

Reputation: 10646

You can use something like usort and strnatcasecmp.

For example:

function sort_2d_asc($array, $key) {
    usort($array, function($a, $b) use ($key) {
        return strnatcasecmp($a[$key], $b[$key]);
    });

    return $array;
}

function sort_2d_desc($array, $key) {
    usort($array, function($a, $b) use ($key) {
        return strnatcasecmp($b[$key], $a[$key]);
    });

    return $array;
}

$unsorted = array(
    'desert' => array(
        'time' => '1339902235',
        'name' => 'desert.jpg'
    ),
    'sea' => array(
        'time' => '1339900801',
        'name' => 'sea.jpg'
    ),
    'mountain' => array(
        'time' => '1339902285',
        'name' => 'mountain.jpg'
    ),
);

$sorted = sort_2d_asc($unsorted, 'time');

Upvotes: 5

Related Questions