Switch two items in associative array

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

Example:

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


        
17条回答
  •  [愿得一人]
    2021-02-05 13:04

    Here's my version of the swap function:

    function array_swap_assoc(&$array,$k1,$k2) {
      if($k1 === $k2) return;  // Nothing to do
    
      $keys = array_keys($array);  
      $p1 = array_search($k1, $keys);
      if($p1 === FALSE) return;  // Sanity check...keys must exist
    
      $p2 = array_search($k2, $keys);
      if($p2 === FALSE) return;
    
      $keys[$p1] = $k2;  // Swap the keys
      $keys[$p2] = $k1;
    
      $values = array_values($array); 
    
      // Swap the values
      list($values[$p1],$values[$p2]) = array($values[$p2],$values[$p1]);
    
      $array = array_combine($keys, $values);
    }
    

提交回复
热议问题