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 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址