Switch two items in associative array

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

Example:

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


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

    Arrays in php are ordered maps.

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

    doesn't mean that that the first element is 'apple'=>'sweet' and the last - 'banana'=>'yellow' just because you put 'apple' first and 'banana' last. Actually, 'apple'=>'sweet' will be the first and 'banana'=>'yellow' will be the second because of alphabetical ascending sort order.

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

    if the array comes from the db, add a sort_order field so you can always be sure in what order the elements are in the array.

    0 讨论(0)
  • 2021-02-05 13:21
    function arr_swap_keys(array &$arr, $key1, $key2, $f_swap_vals=false) {
       // if f_swap_vals is false, then
       // swap only the keys, keeping the original values in their original place
       // ( i.e. do not preserve the key value correspondence )
       // i.e. if arr is (originally)
       // [ 'dog' => 'alpha', 'cat' => 'beta', 'horse' => 'gamma' ]
       // then calling this on arr with, e.g. key1 = 'cat', and key2 = 'horse'
       // will result in arr becoming: 
       // [ 'dog' => 'alpha', 'horse' => 'beta', 'cat' => 'gamma' ]
       // 
       // if f_swap_vals is true, then preserve the key value correspondence
       // i.e. in the above example, arr will become:
       // [ 'dog' => 'alpha', 'horse' => 'gamma', 'cat' => 'beta' ]
       // 
       // 
    
       $arr_vals = array_values($arr); // is a (numerical) index to value mapping
       $arr_keys = array_keys($arr);   // is a (numerical) index to key mapping
       $arr_key2idx = array_flip($arr_keys);
       $idx1 = $arr_key2idx[$key1];
       $idx2 = $arr_key2idx[$key2];
       swap($arr_keys[$idx1], $arr_keys[$idx2]);
       if ( $f_swap_vals ) {
          swap($arr_vals[$idx1], $arr_vals[$idx2]);
       }
       $arr = array_combine($arr_keys, $arr_vals);
    }
    
    function swap(&$a, &$b) {
       $t = $a;
       $a = $b;
       $b = $t;
    }
    
    0 讨论(0)
  • 2021-02-05 13:23

    There is an easy way:

    $sourceArray = array(
        'apple'      => 'sweet',
        'grapefruit' => 'bitter',
        'pear'       => 'tasty',
        'banana'     => 'yellow'
    );
    // set new order
    $orderArray = array(
        'apple'      => '', //this values would be replaced
        'pear'       => '',
        'grapefruit' => '',
        //it is not necessary to touch all elemets that will remains the same
    );
    $result = array_replace($orderArray, $sourceArray);
    print_r($result);
    

    and you get:

    $result = array(
      'apple'      => 'sweet',
      'pear'       => 'tasty',
      'grapefruit' => 'bitter',
      'banana'     => 'yellow'
    )
    
    0 讨论(0)
  • 2021-02-05 13:24

    fwiw here is a function to swap two adjacent items to implement moveUp() or moveDown() in an associative array without foreach()

    /**
     * @param array  $array     to modify
     * @param string $key       key to move
     * @param int    $direction +1 for down | -1 for up
     * @return $array
     */
    protected function moveInArray($array, $key, $direction = 1)
    {
        if (empty($array)) {
            return $array;
        }
        $keys  = array_keys($array);
        $index = array_search($key, $keys);
        if ($index === false) {
            return $array; // not found
        } 
        if ($direction < 0) {
            $index--;
        }
        if ($index < 0 || $index >= count($array) - 1) {
            return $array; // at the edge: cannot move
        } 
    
        $a          = $keys[$index];
        $b          = $keys[$index + 1];
        $result     = array_slice($array, 0, $index, true);
        $result[$b] = $array[$b];
        $result[$a] = $array[$a];
        return array_merge($result, array_slice($array, $index + 2, null, true)); 
    }
    
    0 讨论(0)
提交回复
热议问题