Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting array based on child array[0] (unix) value

Tags:

json

arrays

php

I need an array sorted by Unix timestamp values. I attempted to use both ksort and krsort before realising that occasionally the timestamp values might be the same (and you cannot have duplicate keys in arrays).

Here's an example array I may be faced with:

$array = array(
    [
        "unix"      => 1556547761, // notice the two duplicate unix values
        "random"    => 4
    ],
    [
        "unix"      => 1556547761,
        "random"    => 2
    ],
    [
        "unix"      => 1556547769,
        "random"    => 5
    ],
    [
        "unix"      => 1556547765, // this should be in the 3rd position
        "random"    => 9
    ]
);

So what I'm trying to do is sort them all based on each child arrays unix value, however I cannot figure out how to do so. I have tried countless insane ways (including all other sort functions and many, many for loops) to figure it out - but to no avail.

All help is appreciated.

like image 686
GROVER. Avatar asked Aug 31 '26 23:08

GROVER.


1 Answers

You can use usort which sort your array by given function

Define function as:

function cmpByUnix($a, $b) {
    return $a["unix"] - $b["unix"];
}

And use with: usort($array, "cmpByUnix");

Live example: 3v4l

Notice you can also use asort($array); but this will compare also the "random" field and keep the key - if this what you need then look at Mangesh answer

like image 54
dWinder Avatar answered Sep 03 '26 16:09

dWinder