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

时间:2017-03-29 16:19:41

标签: php arrays sorting

我需要按特定顺序对数组进行排序,按键排序。我知道我需要做类似下面的事情,但尝试了很多不同的变体,无法得到我需要的结果。

有人可以帮忙吗?

下面是一个数组的例子,我正在寻找的结果是:连接性|联络中心|云与云主持|业务连续性

  

$ solutions = Array([业务连续性] =>业务连续性   [Connectivity] =>连通性[Cloud&托管] =>云托管   [联络中心] =>联络中心)

    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 个答案:

答案 0 :(得分:0)

这是一种方法:

// 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);

另一种方式:

// 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));

如果你愿意,你可以把它作为一个单行。

$solutions = array_filter(array_merge(array_fill_keys($custom, null), $solutions));