按时间创建和排序新数组

问题描述:

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

我有一个与此类似的数组 p>

  Array 
  (
 [0] =>数组
(
 [展示名称] =>白领
 [air_time] => 1310590800 
)
 
 [1] =>数组
(\  n [showname] => Chopped 
 [air_time] => 1310590800 
)
 
 [2] =>数组
(
 [展示名称] =>隐蔽事务
 [air_time] =  > 1310587200 
)
} ...等
  code>  pre> 
 
 

我想要创建一个按air_time排序的新数组。例如包含相同的所有节目 air_time应该是[0]然后是[1]然后是[2]等。 p>

我想要的输出示例如下: p>

  Array 
(
 [0] =>数组
(
 [时间] => 1310590800 
 [显示] =>数组
(
 [名称] =>白色 Collar 
 [name] => Chopped 
)
 
)  
 
 [1] => 数组
(
 [时间] => 1310587200 
 [显示] =>数组
(
 [名称] =>隐蔽事务
)
 
)
} 
 
   code>  pre> 
 
 

我一直在寻找不同的数组方法,比如multisort,但我无法弄明白。 p>

你能指点我吗? 在正确的方向? 谢谢 p>

更新 strong>我知道如何按时间正常排序数组,我只是不知道如何分离和分组具有相同时间的元素 p > div>

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

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