Switch two items in associative array

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

Example:

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


        
17条回答
  •  悲哀的现实
    2021-02-05 13:13

    Not entirely sure if this was mentioned, but, the reason this is tricky is because it's non-indexed.

    Let's take:

    $arrOrig = array(
      'fruit'=>'pear',
      'veg'=>'cucumber',
      'tuber'=>'potato'
    );
    

    Get the keys:

    $arrKeys = array_keys($arrOrig);
    print_r($arrKeys);
    Array(
     [0]=>fruit
     [1]=>veg
     [2]=>tuber
    )
    

    Get the values:

    $arrVals = array_values($arrOrig);
    print_r($arrVals);
    Array(
      [0]=>pear
      [1]=>cucumber
      [2]=>potato
    )
    

    Now you've got 2 arrays that are numerical. Swap the indices of the ones you want to swap, then read the other array back in in the order of the modified numerical array. Let's say we want to swap 'fruit' and 'veg':

    $arrKeysFlipped = array_flip($arrKeys);
    print_r($arrKeysFlipped);
    Array (
     [fruit]=>0
     [veg]=>1
     [tuber]=>2
    )
    $indexFruit = $arrKeysFlipped['fruit'];
    $indexVeg = $arrKeysFlipped['veg'];
    $arrKeysFlipped['veg'] = $indexFruit;
    $arrKeysFlipped['fruit'] = $indexVeg;
    print_r($arrKeysFlipped);
    Array (
     [fruit]=>1
     [veg]=>0
     [tuber]=>2
    )
    

    Now, you can swap back the array:

    $arrKeys = array_flip($arrKeysFlipped);
    print_r($arrKeys);
    Array (
     [0]=>veg
     [1]=>fruit
     [2]=>tuber
    )
    

    Now, you can build an array by going through the oringal array in the 'order' of the rearranged keys.

    $arrNew = array ();
    foreach($arrKeys as $index=>$key) {
      $arrNew[$key] = $arrOrig[$key];
    }
    print_r($arrNew);
    Array (
     [veg]=>cucumber
     [fruit]=>pear
     [tuber]=>potato
    )
    

    I haven't tested this - but this is what I'd expect. Does this at least provide any kind of help? Good luck :)

    You could put this into a function $arrNew = array_swap_assoc($key1,$key2,$arrOld);

     0) {
               $arrKeys = array_keys($arrOld);
               $arrFlip = array_flip($arrKeys);
               $indexA = $arrFlip[$key1];
               $indexB = $arrFlip[$key2];
               $arrFlip[$key1]=$indexB;
               $arrFlip[$key2]=$indexA;
               $arrKeys = array_flip($arrFlip);
               foreach($arrKeys as $index=>$key) {
                 $arrNew[$key] = $arrOld[$key];
               }
           } else {
               $arrNew = $arrOld;
           }
           return $arrNew;
        }
    }
    ?>
    

    WARNING: Please test and debug this before just using it - no testing has been done at all.

提交回复
热议问题