首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP -比较关联数组与自定义列表和排序以进行匹配

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

Stack Overflow用户
提问于 2017-03-29 16:19:40
回答 1查看 98关注 0票数 1

我需要按特定的顺序对数组进行排序,按键进行排序。我知道我需要做一些像下面这样的事情,但是尝试了很多不同的方法,但无法得到我想要的结果。

有人能帮忙吗?

数组的一个例子如下所示,我正在寻找的结果是:连接性,连络中心,维修站,云,托管,业务连续性。

$solutions =数组(业务连续性=>业务连续性连接=>连接云和托管=>云托管联系中心=>联系人中心)

代码语言:javascript
复制
    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");
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-03-29 16:30:49

有一种方法可以做到:

代码语言:javascript
复制
// 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);

另一种方式是:

代码语言:javascript
复制
// 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));

如果你愿意的话,你可以把它做成一条线。

代码语言:javascript
复制
$solutions = array_filter(array_merge(array_fill_keys($custom, null), $solutions));
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43098979

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档