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?

Viktors
  • 935
  • 3
  • 13
  • 33
  • 1
    check this related issue: http://stackoverflow.com/questions/2699086/php-sort-multidimensional-array-by-value – Joseph Feb 07 '12 at 02:46

2 Answers2

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.

jonstjohn
  • 59,650
  • 8
  • 43
  • 55
0

You could try something like this:

http://us3.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);
Joseph at SwiftOtter
  • 4,276
  • 5
  • 37
  • 55