2011-07-13 49 views
1

某种新的阵列我有类似这样创建和时间

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 

我想克里特由air_time排序的新数组的数组。例如含有相同air_time所有节目应当在[0]然后[1]→[2]等。

输出我想的一个例子是这样的:

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

     ) 

    [1] => Array 
     (
      [time] => 1310587200 
      [shows] => Array 
       (
        [name] => Covert Affairs 
       ) 

     ) 
} 

我已经一直在寻找像multisort这样的不同数组方法,但我无法弄清楚。

您能否指点我正确的方向?感谢

更新我知道如何在阵列通常按照时间排序,我只是不知道,具有相同的时间

+0

[\ [PHP \]对多维数组进行排序](http://stackoverflow.com/questions/648405/php-sort-a-multi-dimensional-array) –

回答

0

这并不难,如果你围绕它的头。顺便说一下,您不能拥有多个具有相同键名的数组元素。

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

尝试使用我怎样才能分离和族元素。提供的链接有几个工作示例。