1

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] => 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

1

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.