簡體   English   中英

PHP:重新排序關聯數組

[英]PHP: re order associative array

在 php 中,我希望能夠通過將元素移動到數組中的某些位置來重新排序關聯數組。 不需要排序,只是我選擇的重新排序。

例如,假設我有一個關聯數組,如下所示:

array(
 'a' => 'Element A',
 'b' => 'Element B',
 'c' => 'Element C',
);

在一種情況下,我可能想在 B 之前移動 C 並得到以下結果:

array(
 'a' => 'Element A',
 'c' => 'Element C',
 'b' => 'Element B',
);

或者在另一種情況下,我可能想在 A 之前移動 C 並得到以下結果:

array(
 'c' => 'Element C',
 'a' => 'Element A',
 'b' => 'Element B',
);

我想展示的只是一種方法,用於說“嘿,我想在另一個數組元素之前移動這個數組元素”或“嘿,我想移動這個數組元素以確保它在另一個數組之后元素'

希望這是有道理的!

提前感謝任何願意幫助我的人

例如,對於自定義排序,您可以創建一個數組,該數組是鍵的所需順序,然后將值與它們相關聯。 例子:

$input = array("a"=>"Element A","b"=>"Element B","c"=>"Element C");
$order = array("c","a","b");
$out = array();
foreach($order as $k) {
    $out[$k] = $input[$k];
}

$out的元素將按照指定的順序排列。

$arr = array(
  'a' => 1,
  'b' => 2,
  'move me' => 9,
  'c' => 3,
  'd' => 4,
);

嘿,我想在 ['b'] 之前移動 ['move me']。 我只用 4 行代碼就可以做到!

$i = 0; foreach($arr as &$val) $val = array('sort' => (++$i * 10), 'val' => $val);
$arr['move me']['sort'] = $arr['b']['sort'] - 5;
uasort($arr, function($a, $b) { return $a['sort'] > $b['sort']; });
foreach($arr as &$val) $val = $val['val'];




為了方便使用,我做了一個函數:

move_item($arr, 'move me', 'up'); //move it one up
move_item($arr, 'move me', 'down'); //move it one down
move_item($arr, 'move me', 'top'); //move it to top
move_item($arr, 'move me', 'bottom'); //move it to bottom

move_item($arr, 'move me', -1); //move it one up
move_item($arr, 'move me', 1); //move it one down
move_item($arr, 'move me', 2); //move it two down

move_item($arr, 'move me', 'up', 'b'); //move it before ['b']
move_item($arr, 'move me', -1, 'b'); //move it before ['b']
move_item($arr, 'move me', 'down', 'b'); //move it after ['b']
move_item($arr, 'move me', 1, 'b'); //move it after ['b']
move_item($arr, 'move me', 2, 'b'); //move it two positions after ['b']

//Special syntax, to swap two elements:
move_item($arr, 'a', 0, 'd'); //Swap ['a'] with ['d']


例子:

 move_item($arr, 'move me', 'up'); //move it one up move_item($arr, 'move me', 'down'); //move it one down move_item($arr, 'move me', 'top'); //move it to top move_item($arr, 'move me', 'bottom'); //move it to bottom move_item($arr, 'move me', -1); //move it one up move_item($arr, 'move me', 1); //move it one down move_item($arr, 'move me', 2); //move it two down move_item($arr, 'move me', 'up', 'b'); //move it before ['b'] move_item($arr, 'move me', -1, 'b'); //move it before ['b'] move_item($arr, 'move me', 'down', 'b'); //move it after ['b'] move_item($arr, 'move me', 1, 'b'); //move it after ['b'] move_item($arr, 'move me', 2, 'b'); //move it two positions after ['b'] //Special syntax, to swap two elements: move_item($arr, 'a', 0, 'd'); //Swap ['a'] with ['d']


我希望這可以幫助很多人,因為它是一個很棒的功能! :D

如果你想交換兩個值,你可以創建一個這樣的函數:

function array_swap($key1, $key2, $array) {
        $newArray = array ();
        foreach ($array as $key => $value) {
            if ($key == $key1) {
                $newArray[$key2] = $array[$key2];
            } elseif ($key == $key2) {
                $newArray[$key1] = $array[$key1];
            } else {
                $newArray[$key] = $value;
            }
        }
        return $newArray;
    }

這里有很多困難的方法:) 事實上,您可以利用array_slice()的保留鍵功能。

$new_element = array('new_key' => 'value');

// if needed, find the insertion index by key
$index = array_search('key to search', array_keys($old_array));

// add element at index (note the last array_slice argument)
$new_array = array_slice($old_array, 0, $index+1, true) + $new_element + array_slice($old_array, $index+1, null, true);

不幸的是, array_splice不適用於關聯數組,所以這里有點混亂:

$keys = array_keys($arr);
$values = array_values($arr);

$keyIndex = array_search($someKey, $keys);
array_splice($keys, $keyIndex, 1);
array_splice($values, $keyIndex, 1);

$insertIndex = 1;
array_splice($keys, $insertIndex, 0, array($someKey));
array_splice($values, $insertIndex, 0, array($arr[$someKey]));

$arr = array_combine($keys, $values);

我根據這里的一個答案制作了一個功能。 它需要對 assoc 數組的數組進行排序,再加上應該對其進行排序的鍵數組

// $data = array of assoc array
// $newKeysOrder = array("c","a","b");
function resort_assoc_array_by_keys($data, $newKeysOrder) {
  foreach($data as $v) {
    $out = [];
    foreach($newKeysOrder as $k) {
      $out[$k] = $v[$k];
    }  
    $new[] = $out;
  }
  return $new;
}

我最喜歡 luky 的回答,但它需要指定所有的鍵。 大多數情況下,您只想在數組的開頭對鍵的子集進行排序。 此功能將有助於:

function reorder_assoc_array(
  $cur,   // current assoc array 
  $order  // array conaining ordered (subset of) keys in $cur
) {
  $result = [];
  // first copy ordered key/values to result array
  foreach($order as $key) {
    $result[$key] = $cur[$key];
    // unset key in original array
    unset($cur[$key]);
  }
  // ... then copy all remaining keys that were not given in $order
  foreach($cur as $key => $value) {
    $result[$key] = $value;
  }
  return $result;
}

例子:

$assoc_arr = [
  'b' => 'bbb',
  'a' => 'aaa',
  'c' => 'ccc',
  'd' => 'ddd'
];

// suppose we want to swap the first two keys and leave the remaining keys as is
$assoc_arr = reorder_assoc_array($assoc_arr, ['a', 'b']);

// ... the order of keys is now a, b, c, d

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM