douju2012 2017-03-29 16:19
浏览 63
已采纳

PHP - 将关联数组与自定义列表进行比较并排序以匹配

I need to sort an array in a particular order, sorting by the keys. I know I need to do something like the below but have tried many different variations of the it and cannot get the result I need.

Can anyone help?

An example of the array is below and th results I am looking for for this would be: Connectivity | Contact Centres | Cloud & Hosting | Business Continuity

$solutions = Array ( [Business Continuity] => business-continuity [Connectivity] => connectivity [Cloud & Hosting] => cloud-hosting [Contact Centres] => contact-centres )

    function reorder_solutions($a, $b){
                    $custom = array('Lines & Calls', 'Mobile', 'Connectivity', 'Wifi', 'LAN', 'UC&C', 'Contact Centres', 'Cloud & Hosting', 'Managed Services', 'Security', 'Business Continuity');

                    foreach ($custom as $k => $v){
                        if ($k == $b) {
                            return 0;
                        }
                        return ($k < $b) ? -1 : 1;
                    }
                }

                uasort($solutions, "reorder_solutions");
  • 写回答

1条回答 默认 最新

  • dream543211 2017-03-29 16:30
    关注

    Here's one way to do it:

    // loop over the $custom array
    foreach ($custom as $key) {
    
        // add each key found in $solutions into a $sorted array
        // (they'll be added in custom order)
        if (isset($solutions[$key])) {
            $sorted[$key] = $solutions[$key];
    
            // remove the item from $solutions after adding it to $sorted
            unset($solutions[$key]);
        }
    }
    
    // merge the $sorted array with any remaining items in $solutions
    $solutions = array_merge($sorted, $solutions);
    

    Another way:

    // create an array using the values of $custom as keys with all empty values
    $custom = array_fill_keys($custom, null);
    
    // merge that array with $solutions (same keys will be overwritten with values
    //  from $solutions, then remove the empty values with array_filter
    $solutions = array_filter(array_merge($custom, $solutions));
    

    You can make it a one-liner if you like.

    $solutions = array_filter(array_merge(array_fill_keys($custom, null), $solutions));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分