Switch two items in associative array

后端 未结 17 1911
自闭症患者
自闭症患者 2021-02-05 12:53

Example:

$arr = array(
  \'apple\'      => \'sweet\',
  \'grapefruit\' => \'bitter\',
  \'pear\'       => \'tasty\',
  \'banana\'     => \'yellow\'
)         


        
17条回答
  •  情深已故
    2021-02-05 13:21

    function arr_swap_keys(array &$arr, $key1, $key2, $f_swap_vals=false) {
       // if f_swap_vals is false, then
       // swap only the keys, keeping the original values in their original place
       // ( i.e. do not preserve the key value correspondence )
       // i.e. if arr is (originally)
       // [ 'dog' => 'alpha', 'cat' => 'beta', 'horse' => 'gamma' ]
       // then calling this on arr with, e.g. key1 = 'cat', and key2 = 'horse'
       // will result in arr becoming: 
       // [ 'dog' => 'alpha', 'horse' => 'beta', 'cat' => 'gamma' ]
       // 
       // if f_swap_vals is true, then preserve the key value correspondence
       // i.e. in the above example, arr will become:
       // [ 'dog' => 'alpha', 'horse' => 'gamma', 'cat' => 'beta' ]
       // 
       // 
    
       $arr_vals = array_values($arr); // is a (numerical) index to value mapping
       $arr_keys = array_keys($arr);   // is a (numerical) index to key mapping
       $arr_key2idx = array_flip($arr_keys);
       $idx1 = $arr_key2idx[$key1];
       $idx2 = $arr_key2idx[$key2];
       swap($arr_keys[$idx1], $arr_keys[$idx2]);
       if ( $f_swap_vals ) {
          swap($arr_vals[$idx1], $arr_vals[$idx2]);
       }
       $arr = array_combine($arr_keys, $arr_vals);
    }
    
    function swap(&$a, &$b) {
       $t = $a;
       $a = $b;
       $b = $t;
    }
    

提交回复
热议问题