Help me sort this php array using usort ()

I have a data structure that looks like

Array
(
[0] => Array
    (
        [0] => something
        [1] => 1296986500
    )

[1] => Array
    (
        [0] => something else
        [1] => 1296600100
    )

[2] => Array
    (
        [0] => another thing
        [1] => 1296831265
    )
)

I am trying to sort an array based on an integer, which is a unix timestamp. The following function looks right to me, but does not sort as I want.

function cmp($a, $b)
{
    if ($a[1] == $b[1]) {
        return 0;
    }
    return ($a[1] < $b[1]) ? -1 : 1;
}

Note  when calling this function inside a class, the OO syntax is as follows

uasort($_data, array($this, 'cmp'));
+3
source share
2 answers

Sorts your timestamps in ascending order; for descending order, flip the second comparison (i.e. change $a[1] < $b[1]to $a[1] > $b[1]):

function cmp($a, $b)
{
    if ($a[1] == $b[1]) {
        return 0;
    }
    return ($a[1] > $b[1]) ? -1 : 1;
}
+3
source

You can set the timestamp as a pivot point. And use array_multisort ().

<?php
// Obtain a list of columns
foreach ($data as $key => $row) {
    $time[$key]  = $row[1]; //unix timestamp 
}


array_multisort( $time, SORT_ASC, $data);
?> 
+2
source

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


All Articles