Switch two items in associative array

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

Example:

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


        
17条回答
  •  萌比男神i
    2021-02-05 13:13

    Well it's just a key sorting problem. We can use uksort for this purpose. It needs a key comparison function and we only need to know that it should return 0 to leave keys position untouched and something other than 0 to move key up or down.

    Notice that it will only work if your keys you want to swap are next to each other.

     'sweet',
      'grapefruit' => 'bitter',
      'pear'       => 'tasty',
      'banana'     => 'yellow'
    );
    
    uksort(
        $arr,
        function ($k1, $k2) {
            if ($k1 == 'grapefruit' && $k2 == 'pear') return 1;
            else return 0;
        }
    );
    
    var_dump($arr);
    

提交回复
热议问题