It is necessary to swap two elements in the array with arbitrarily specified keys. For example, there is an array

['b' => 0, 'a' => 1, 'c' => 2] 

need to make an array of it

 ['b' => 0, 'c' => 2, 'a' => 1] 

(swap the values ​​with the keys 'a' and 'c' ).

  • And what will change as a result of this? What is the idea? - Alexey Shimansky
  • @ Alexey Shimansky, foreach traversal order? Or does php not guarantee it? - Qwertiy
  • yes, the traversal order for foreach will be changed. Actually the elements of the array are displayed on the screen and the original order turned out to be wrong, but I can not change it. - Oboroten
  • one
    And how is the data obtained? From the database? Can it be easier to change them at that level? And if there is more data and the order will be all wrong? Or is it guaranteed only three array elements in which the last two are confused? - Alexey Shimansky
  • The easiest way to add an array with the values ​​of keys in the order in which you want to bypass, i.e. $keys = ['b','c','a'] . Iterate this array and access the original by key value. - teran

2 answers 2

http://ideone.com/XaEs1f

 <?php $a = array('b' => 0, 'a' => 1, 'c' => 2); print_r($a); $keys = array_keys($a); $i = array_search('a', $keys); $j = array_search('c', $keys); if ($i !== false && $j !== false) { $keys[$i] = 'c'; $keys[$j] = 'a'; } $b = array(); foreach ($keys as $key) $b[$key] = $a[$key]; print_r($b); 

I have no idea how normal this is, but it seems to work ...

     $array = array('b' => 0, 'a' => 1, 'c' => 2); $array_order = array('b', 'c', 'a'); $sorted_array = array_merge(array_flip($array_order), $array); // или $sorted_array = array_replace(array_flip($array_order), $array); 

    array_flip swaps keys and values
    array_merge merges arrays, with replacement by the values ​​of the second array
    array_replace replaces key values ​​of the first array with values ​​of the second

    Taken from here https://stackoverflow.com/questions/348410/sort-an-array-by-keys-based-on-another-array

    • And if we don’t know the original order of the keys (i.e., we do not have $ array_order)? We only know that you need to swap 2 keys in places. - Oboroten
    • @Oborotenby, that is, you and an array of different lengths can have all the elements in general, but only two of them may not be in their proper places and having changed them everything will be perfect? And why, having changed only them, regardless of the rest of the random sequence, the result will satisfy? * scratching a turnip * - Alexey Shimansky
    • @Oborotenby, I agree with Alexey, maybe you are solving the problem from the wrong side. If you do not have a specific task to change random elements in places in the array, but there is some subtext, then most likely the problem can be solved at the stage of the formation of the array - apelsinka223