Jump to content

sort a multidimensional array...


mkosmosports

Recommended Posts

Hey,

 

Ive got the following md array

 

Array
(
    [0] => Array
        (
            [id] => 3
            [title] => Title
            [date] => Oct 29 08:11
        )

    [1] => Array
        (
            [id] => 5
            [title] => Title
            [date] => Oct 29 08:25
        )

    [2] => Array
        (
            [id] => 6
            [title] => Title
            [date] => Oct 29 08:18
        )

    [3] => Array
        (
            [id] => 4
            [title] => Title
            [date] => Oct 29 08:16
        )

 

What I want to do is sort the 1st level array by the date in the second level array (with the keys getting reordered accordingly) so this one would read as follows after:

 

 

Array
(
    [0] => Array
        (
            [id] => 6
            [title] => Title
            [date] => Oct 29 08:18
        )

    [1] => Array
        (
            [id] => 5
            [title] => Title
            [date] => Oct 29 08:17
        )

    [2] => Array
        (

            [id] => 4
            [title] => Title
            [date] => Oct 29 08:16
        )

    [3] => Array
        (
            [id] => 3
            [title] => Title
            [date] => Oct 29 08:11
        )

 

Any ideas?

 

Thanks!

Link to comment
Share on other sites

try

<?php
$data = array
(
    0 => array
        (
            'id' => 3,
            'title' => 'Title',
            'date' => 'Oct 29 08:11'
        ),

    1 => array
        (
            'id' => 5,
            'title' => 'Title',
            'date' => 'Oct 29 08:25'
        ),

    2 => array
        (
            'id' => 6,
            'title' => 'Title',
            'date' => 'Oct 29 08:18'
        ),

    3 => array
        (
            'id' => 4,
            'title' => 'Title',
            'date' => 'Oct 29 08:16'
        )
);

function datesort ($a, $b)
{
    $da = strtotime ($a['date']);
    $db = strtotime ($b['date']);
    return ($db - $da);
}

usort ($data, 'datesort');

echo '<pre>', print_r($data, true), '</pre>';
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.