0

I have merge two array with php function "merge_recursive" (both came from sql query) all of them have a common field [date] is it possible to sort array[new] by [date] field ?

       [new] => Array
            (
                [0] => Array
                    (
                        [user] => 8888
                        [user_image] => 0j1kjjzdv3ez07a0ee4lnmjb7_163.jpeg
                        [favorite_id] => 2
                        [date] => 1328579091
                        [images_id] => 4
                        [image] => 0j1kjjzdv3ez07a0ee4lnmjb7_163.jpeg
                        [text] => 
                        [favorite_user] => 8888
                        [favorite_user_image] => 0j1kjjzdv3ez07a0ee4lnmjb7_163.jpeg
                    )

                [1] => Array
                    (
                        [user] => 8888
                        [user_image] => 0j1kjjzdv3ez07a0ee4lnmjb7_163.jpeg
                        [favorite_id] => 5
                        [date] => 1328578954
                        [images_id] => 2
                        [image] => flw3utn9igiqh7dtt2o61ydf8_174.jpeg
                        [text] => 3
                        [favorite_user] => 6666
                        [favorite_user_image] => flw3utn9igiqh7dtt2o61ydf8_174.jpeg
                    )

                [2] => Array
                    (
                        [user] => 8888
                        [user_image] => 0j1kjjzdv3ez07a0ee4lnmjb7_163.jpeg
                        [image] => 0j1kjjzdv3ez07a0ee4lnmjb7_163.jpeg
                        [image_id] => 4
                        [date] => 1328579081
                        [text] => 
                        [image_date] => 1328577934
                        [comments] => 0
                    )

            )

I want that aray will be sort like (example below)

[1] = Array
(
)
[0] = Array
(
)
[2] = Array
(
)

is it possible?

1

2 Answers 2

1

You can use array_multisort, which does exactly what you want.

$dates = array();
foreach ($new as $key => $value) { // $new is your array
    $dates[$key] = $value['date'];
}
array_multisort($dates, SORT_ASC, $new);

This is easily extendible with multiple sort criteria.

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

Comments

0

You could try something like this:

https://www.php.net/manual/en/function.uasort.php

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

uasort($input, compareDate);

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.