Switch two items in associative array

后端 未结 17 1910
自闭症患者
自闭症患者 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
    )
    

提交回复
热议问题