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
https://forums.phpfreaks.com/topic/76701-sort-a-multidimensional-array/
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>';
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.