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

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

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

任何人都可以帮忙吗? p>

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

$ solutions = Array([业务连续性] =&gt;业务连续性 [连接] =&gt;连接[云和托管] =&gt ;云托管 [联络中心] =&gt;联络中心) p> blockquote>

  function reorder_solutions($ a,$ b){
 $  custom = array('Lines&amp; Calls','Mobile','Connectivity','Wifi','LAN','UC&amp; C','Contact Centers','Cloud&amp; Hosting','Managed Services',  '安全','业务连续性'); 
 
 foreach($ custom as $ k =&gt; $ v){
 if($ k == $ b){
 return 0; 
} 
 返回($ k&lt; $ b)?  -1:1; 
} 
} 
 
 uasort($ solutions,“reorder_solutions”); 
  code>  pre> 
  div>

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