Home:ALL Converter>sorting array based on child array[0] (unix) value

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

Ask Time:2019-04-30T01:26:57         Author:GROVER.

Json Formatter

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.

Author:GROVER.,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/55908206/sorting-array-based-on-child-array0-unix-value
dWinder :

You can use usort which sort your array by given function\n\nDefine function as:\n\nfunction cmpByUnix($a, $b) {\n return $a[\"unix\"] - $b[\"unix\"];\n}\n\n\nAnd use with: usort($array, \"cmpByUnix\");\n\nLive example: 3v4l\n\nNotice 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",
Rakesh Jakhar :

\narray_multisort() — Sort multiple or multi-dimensional arrays\narray_columns() — Return the values from a single column in the input array\n\nYou can use array_multisort() and array_column(), then provide your desired sort order (SORT_ASC or SORT_DESC).\narray_multisort(array_column($array, "unix"), SORT_ASC, $array);\n\nExplanation:\nIn array_multisort(), arrays are sorted by the first array given. You can see we are using array_column($array, "unix"), which means that the second parameter is the order of sorting (ascending or descending) and the third parameter is the original array.\nThis is the result of array_column($array, "unix"):\nArray(\n [0] => 1556547761\n [1] => 1556547761\n [2] => 1556547765\n [3] => 1556547769\n)\n",