2017-03-29 2 views
1

配列を特定の順序でソートし、キーでソートする必要があります。私は以下のようなことをする必要があることを知っていますが、それの多くの異なるバリエーションを試して、必要な結果を得ることはできません。PHP - 連想配列をカスタムリストと比較して一致するように並べ替えよう

誰でも手助けできますか?

配列の例は以下の通りです。私はこれを探しています。コンタクトセンター|クラウド&ホスティング|事業継続

$ソリューション=アレイ([ビジネス継続性] =>ビジネス継続性 [接続] =>接続[クラウド&ホスティング] =>クラウド型ホスティング [コンタクトセンター] =>コンタクトセンター)ここで

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

答えて

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

好きな場合は1ライナーにすることができます。

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

これは、イムはアンパサンドと名が正しく注文されていないと、リストの最後に置かれている問題を持つものの、動作しているようです...奇妙 – LeeTee

+0

奇妙です。これはあなたの値を使って私のために大丈夫とテストされました。何らかの理由で '$ custom'にキーが見つからなかった場合、キーは配列の最後に置かれます。 –

+0

それはPHPのバージョンに依存していないようです:https://3v4l.org/im5sG –

関連する問題