开发者

Create and sort new array by time

I have an array similar to this

Array
(
    [0] => Array
        (
            [showname] => White Collar
            [air_time] => 1310590800
        )

    [1] => Array
        (
            [showname] => Chopped
            [air_time] => 1310590800
        )

    [2] => Array
        (
            [showname] => Covert Affairs
            [air_time] => 1310587200
        )
    } ... etc

I want to crete a new array that is sorted by air_time. for example all shows containing the same air_time should be in [0] then [1] then [2] etc..

An example of the output i would like is this:

Array
(
    [0] => Array
        (
            [time] => 1310590800
            [shows] => Array
                (
                    [name] => White Collar
                    [name] => Chopped
                )

        )

    [1] => Array
        (
            [time] => 1310587200
            [shows] => Array
                (
                    [name]开发者_如何学C => Covert Affairs
                )

        )
}

I've been looking at different array methods like multisort but i wasn't able to figure it out.

Could you point me in the right direction? thanks

update i know how to sort the array normally by time, i just dont know how can i separate and group elements that have the same time


Try using usort. The provided link has several working examples.


It's not that hard if you wrap your head around it. By the way, you can't have multiple array elements with the same key name.

$shows = array(
    array(
        'showname' => 'White Collar',
        'air_time' => 1310590800
    ),
    array(
        'showname' => 'Covert Affairs',
        'air_time' => 1310587200
    ),
    array(
        'showname' => 'Chopped',
        'air_time' => 1310590800
    )
);

/* Sort by air_time (descending) */
usort($shows, function ($a, $b) {
    return ($b['air_time'] - $a['air_time']);
});


/* Regroup array (utilizing the fact that the array is ordered) */
$regrouped = array();
$c = 0;
foreach ($shows as $show) {
    if ($c > 0 && $regrouped[$c - 1]['time'] === $show['air_time']) {
        $regrouped[$c - 1]['shows'][] = $show['showname'];
    } else {
        $regrouped[] = array('time'  => $show['air_time'],
                             'shows' => array($show['showname']));
        $c++;
    }
}

print_r($regrouped);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜