Switch two items in associative array

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

Example:

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


        
17条回答
  •  余生分开走
    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)); 
    }
    

提交回复
热议问题