doucaishou0074 2011-07-13 16:28
浏览 88
已采纳

按时间创建和排序新数组

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

  • 写回答

2条回答 默认 最新

  • dongtu0088 2011-07-14 12:26
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用