1

I know this would be an easy one but I don't get it. All answered I found on the net was... too complex to me, maybe.

Here is my typical array:

array(
(int) 0 => array(
    'Conversation' => array(
        'id' => '1',
        'created' => '2012-08-04 00:00:00'
    ),
    'ConversationUser' => array(
        (int) 0 => array(
            'id' => '1'
        ),
        (int) 1 => array(
            'id' => '2'
        )
    )
),
(int) 1 => array(
    'Conversation' => array(
        'id' => '2',
        'created' => '2012-08-01 00:00:00'
    ),
    'ConversationUser' => array(
        (int) 0 => array(
            'id' => '1'
        ),
        (int) 1 => array(
            'id' => '2'
        )
    )
));

I want to sort my data with ['Conversation']['created'] date, asc or desc.

Any simple answer ? :P

P.S. I can't use MYSQL sort, I retrieve the data one by one and create that array.

  • You may want to read up on [`uasort()`](http://php.net/uasort). You'll just have to code a little function to do the array access and date comparison then. – mario Aug 05 '12 at 17:54
  • `P.S. I can't use MYSQL sort, I retrieve the data one by one and create that array.` The two do not contrast each other. You can use MySQL sort **and** iterate the results one by one to create the array. Please share your query with us. – Madara's Ghost Aug 05 '12 at 17:54
  • possible duplicate of [How do I sort a multidimensional array in php](http://stackoverflow.com/questions/96759/how-do-i-sort-a-multidimensional-array-in-php) – mario Aug 05 '12 at 17:56

4 Answers4

3

Use usort() :

usort($your_array, function($a, $b){
    $a = strtotime($a['Conversation']['created']);
    $b = strtotime($b['Conversation']['created']);

    if ($a == $b) {
        return 0;
    }
    return ($a > $b) ? -1 : 1;
});
Jérôme Boé
  • 2,752
  • 4
  • 21
  • 32
2

You can use array_multisort to do this:

// $data is your array from the example
// first obtain the rows for sorting
$sortkeys = array();
foreach ($data as $row) {
    $sortkeys[] = $row['Conversation']['created'];
}

// sort $data according to $sortkeys
array_multisort($sortkeys, $data);
var_dump($data);
complex857
  • 20,425
  • 6
  • 51
  • 54
1

You should have a look to uksort() and usort() functions, which let you customize the way arrays are sorted.

Either the solution is simple or complex, remember what Einstein said once: "Things should be always done as simple as possible, but never simpler than they really are".

If you have some trouble with these functions, we can give you further clues ;-)

Claudi
  • 5,224
  • 17
  • 30
0

You can use usort() (or, to maintain index association, uasort(). Example: (assumes your array is $arr):

usort($arr, function($a, $b) {
    return
    preg_replace('/\D/', '', $b['Conversation']['created'])
    >
    preg_replace('/\D/', '', $a['Conversation']['created']);
});

That will sort descending. Change > to < for ascending.

Mitya
  • 33,629
  • 9
  • 60
  • 107