Rémi Barbalat
Rémi Barbalat

Reputation: 27

PHP sorting 3 dimensional array

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.

Upvotes: 2

Views: 4271

Answers (4)

complex857
complex857

Reputation: 20753

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);

Upvotes: 3

Mitya
Mitya

Reputation: 34556

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.

Upvotes: 0

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;
});

Upvotes: 3

Claudi
Claudi

Reputation: 5416

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 ;-)

Upvotes: 1

Related Questions