Switch two items in associative array

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

Example:

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


        
17条回答
  •  伪装坚强ぢ
    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

提交回复
热议问题