3

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.

0

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

4 Comments

Ooh clever and clean, let me give it a shot
Nice of you to promote someone else's answer! But your answer is exactly what I wanted! Just out of curiosity, is there a way to flip this array using the current method without array_reverse? Or is it just easier to do it with that
I guess you can just change the function to $b["unix"] - $a["unix"] - notice the $b at the beginning makes it DESC. If this help you you may mark it as accepted
Oh doy, obviously - why didn't I think of that? Hahahaha
3

array_multisort() — Sort multiple or multi-dimensional arrays

array_columns() — Return the values from a single column in the input array

You can use array_multisort() and array_column(), then provide your desired sort order (SORT_ASC or SORT_DESC).

array_multisort(array_column($array, "unix"), SORT_ASC, $array);

Explanation:

In 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.

This is the result of array_column($array, "unix"):

Array(
    [0] => 1556547761
    [1] => 1556547761
    [2] => 1556547765
    [3] => 1556547769
)

3 Comments

Let me give it a shot! :)
Any chance you can explain how this works a bit better? It's very compact and works, however it lacks explanation.
@GROVER. I have mentioned the explanation in the solution, hope you will understand.
1

This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.

Note:If two members compare as equal, their relative order in the sorted array is undefined.

Refer : https://www.php.net/manual/en/function.asort.php

asort($array);

echo "<pre>";
print_r($array);
echo "</pre>";

It will give you the output as

Array
(
    [1] => Array
        (
            [unix] => 1556547761
            [random] => 2
        )

    [0] => Array
        (
            [unix] => 1556547761
            [random] => 4
        )

    [3] => Array
        (
            [unix] => 1556547765
            [random] => 9
        )

    [2] => Array
        (
            [unix] => 1556547769
            [random] => 5
        )

)

You can keep the array key [1],[0],[3],[2]) as it is Or you can keep it as sequential as per your requirement.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.