Switch two items in associative array

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

Example:

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


        
相关标签:
17条回答
  • 2021-02-05 13:00

    This may or may not be an option depending on your particular use-case, but if you initialize your array with null values with the appropriate keys before populating it with data, you can set the values in any order and the original key-order will be maintained. So instead of swapping elements, you can prevent the need to swap them entirely:

    $arr = array('apple' => null,
                 'pear' => null,
                 'grapefruit' => null,
                 'banana' => null);
    

    ...

    $arr['apple'] = 'sweet';
    $arr['grapefruit'] = 'bitter'; // set grapefruit before setting pear
    $arr['pear'] = 'tasty';
    $arr['banana'] = 'yellow';
    print_r($arr);
    
    >>> Array
    (
        [apple] => sweet
        [pear] => tasty
        [grapefruit] => bitter
        [banana] => yellow
    )
    
    0 讨论(0)
  • 2021-02-05 13:00

    I'll share my short version too, it works with both numeric and associative arrays.

    array array_swap ( array $array , mixed $key1 , mixed $key2 [, bool $preserve_keys = FALSE [, bool $strict = FALSE ]] )
    

    Returns a new array with the two elements swapped. It preserve original keys if specified. Return FALSE if keys are not found.

    function array_swap(array $array, $key1, $key2, $preserve_keys = false, $strict = false) {
        $keys = array_keys($array);
        if(!array_key_exists($key1, $array) || !array_key_exists($key2, $array)) return false;
        if(($index1 = array_search($key1, $keys, $strict)) === false) return false;
        if(($index2 = array_search($key2, $keys, $strict)) === false) return false;
        if(!$preserve_keys) list($keys[$index1], $keys[$index2]) = array($key2, $key1);
        list($array[$key1], $array[$key2]) = array($array[$key2], $array[$key1]);
        return array_combine($keys, array_values($array));
    }
    

    For example:

    $arr = array_swap($arr, 'grapefruit', 'pear');
    
    0 讨论(0)
  • 2021-02-05 13:03

    yeah I agree with Lex, if you are using an associative array to hold data, why not using your logic handle how they are accessed instead of depending on how they are arranged in the array.

    If you really wanted to make sure they were in a correct order, trying creating fruit objects and then put them in a normal array.

    0 讨论(0)
  • 2021-02-05 13:03

    I wrote a function with more general purpose, with this problem in mind.

    1. array with known keys
    2. specify order of keys in a second array ($order array keys indicate key position)

    function order_array($array, $order) {

        foreach (array_keys($array) as $k => $v) {
            $keys[++$k] = $v;
        }
        for ($i = 1; $i <= count($array); $i++) {
            if (isset($order[$i])) {
                unset($keys[array_search($order[$i], $keys)]);
            }
            if ($i === count($array)) {
                        array_push($keys, $order[$i]);
                    } else {
                        array_splice($keys, $i-1, 0, $order[$i]);
                    }
                }
            }
            foreach ($keys as $key) {
                $result[$key] = $array[$key];
            }
            return $result;
        } else {
            return false;
        }
    }
    
    $order = array(1 => 'item3', 2 => 'item5');
    $array = array("item1" => 'val1', "item2" => 'val2', "item3" => 'val3', "item4" => 'val4', "item5" => 'val5');
    
    print_r($array); -> Array ( [item1] => val1 [item2] => val2 [item3] => val3 [item4] => val4 [item5] => val5 ) 
    
    print_r(order_array($array, $order)); -> Array ( [item3] => val3 [item5] => val5 [item1] => val1 [item2] => val2 [item4] => val4 )
    

    I hope this is relevant / helpful for someone

    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
  • 2021-02-05 13:07

    There is no easy way, just a loop or a new array definition.

    0 讨论(0)
提交回复
热议问题