dsy19811981 2016-12-14 23:44
浏览 145
已采纳

php,按值排序数组(星期几)

Is there a simple way to order this array (the days will always be displayed in right order)

  0 => "Thursday,Sunday"
  1 => "Tuesday"
  2 => "Monday"
  3 => "Tuesday,Thursday,Saturday"
  4 => "Tuesday"
  5 => "Monday,Wednesday"
  6 => "Saturday,Sunday"
  8 => "Wednesday"
  9 => "Saturday"
  10 => "Tuesday"
  11 => "Monday,Sunday"

in this ordery (by days of the week)

  2 => "Monday"
  5 => "Monday,Wednesday"
  11 => "Monday,Sunday"
  1 => "Tuesday"
  4 => "Tuesday"
  10 => "Tuesday"
  3 => "Tuesday,Thursday,Saturday"
  7 => "Tuesday,Friday"
  8 => "Wednesday"
  0 => "Thursday,Sunday"
  9 => "Saturday"
  6 => "Saturday,Sunday"

In the end I'll need to define the starting day but hopefully it should be easy to generalize the solution.

Thanks!

UPDATE

Next question is how do I rearrange the

    $day_map = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];

to start from today date('l'). So if today's Fridey I would get

    $rearranged_day_map = ['Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday'];

And the answer to the updated question (the answer to the original question is below):

    //days
    $day_map = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
    //order days to start from tomorrow
    $today = date('N'); // get today's day of the week
    $day_map_rearranged = array_merge(array_slice($day_map, $today),array_slice($day_map, 0, $today));
  • 写回答

2条回答 默认 最新

  • duanqiechui2378 2016-12-15 02:18
    关注

    As others have advised, you'll need to use uasort for this one. What I would do is explode the string first. Then create a default mapping for a day sequence (Mon - Fri) and use that for the sorting.

    Here's the dirty idea:

    // default order
    $day_map = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
    uasort($input_array, function($a, $b) use ($day_map) {
        $c = explode(',', $a); $d = explode(',', $b);
        for($i = 0, $len = count($c); $i < $len; $i++) {
            $d1 = @array_search($c[$i], $day_map);
            $d2 = @array_search($d[$i], $day_map);
            if($d1 == $d2) {
                continue; // skip, check the next column
            }
            return $d1 - $d2;
        }
    });
    

    Sample Out

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)