Switch two items in associative array

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

Example:

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


        
17条回答
  •  逝去的感伤
    2021-02-05 13:11

    Here are two solutions. The first is longer, but doesn't create a temporary array, so it saves memory. The second probably runs faster, but uses more memory:

    function swap1(array &$a, $key1, $key2)
    {
      if (!array_key_exists($key1, $a) || !array_key_exists($key2, $a) || $key1 == $key2) return false;
    
      $after = array();
      while (list($key, $val) = each($a))
      {
        if ($key1 == $key)
        {
          break;
        }
        else if ($key2 == $key)
        {
          $tmp = $key1;
          $key1 = $key2;
          $key2 = $tmp;
          break;
        }
      }
    
      $val1 = $a[$key1];
      $val2 = $a[$key2];
    
      while (list($key, $val) = each($a))
      {
        if ($key == $key2)
          $after[$key1] = $val1;
        else
          $after[$key] = $val;
        unset($a[$key]);
      }
    
      unset($a[$key1]);
      $a[$key2] = $val2;
    
      while (list($key, $val) = each($after))
      {
        $a[$key] = $val;
        unset($after[$key]);
      }
    
      return true;
    }
    
    function swap2(array &$a, $key1, $key2)
    {    
      if (!array_key_exists($key1, $a) || !array_key_exists($key2, $a) || $key1 == $key2) return false;
    
      $swapped = array();
    
      foreach ($a as $key => $val)
      {
        if ($key == $key1)
          $swapped[$key2] = $a[$key2];
        else if ($key == $key2)
          $swapped[$key1] = $a[$key1];
        else
          $swapped[$key] = $val;
      }
    
      $a = $swapped;
    
      return true;
    }
    

提交回复
热议问题