2011-04-08 21 views
14

是否可以在PHP中輕鬆地旋轉數組?PHP:'旋轉'數組?

像這樣: 1,2,3,4 - > 2,3,4,1

是否有某種內置PHP函數呢?

+3

這是一個提示:你需要做的就是刪除第一個元素(「pop」),並將其添加回最後一個元素(「push」)。 – 2011-04-08 23:20:04

+0

[旋轉列表](http://stackoverflow.com/questions/5055418/rotating-a-list) – 2011-04-08 23:21:44

回答

16

目前大多數的答案是正確的,但只有當你不關心你的指標:

$arr = array('foo' => 'bar', 'baz' => 'qux', 'wibble' => 'wobble'); 
array_push($arr, array_shift($arr)); 
print_r($arr); 

輸出:

Array 
(
    [baz] => qux 
    [wibble] => wobble 
    [0] => bar 
) 

要保留你的索引可以這樣做:

$arr = array('foo' => 'bar', 'baz' => 'qux', 'wibble' => 'wobble'); 

$keys = array_keys($arr); 
$val = $arr[$keys[0]]; 
unset($arr[$keys[0]]); 
$arr[$keys[0]] = $val; 

print_r($arr); 

輸出:

Array 
(
    [baz] => qux 
    [wibble] => wobble 
    [foo] => bar 
) 

也許有人可以做旋轉更簡潔比我四線法,但這個工程呢。

20
$numbers = array(1,2,3,4); 
    array_push($numbers, array_shift($numbers)); 
    print_r($numbers); 

輸出

Array 
(
    [0] => 2 
    [1] => 3 
    [2] => 4 
    [3] => 1 
) 
+0

這很好,如果你只是像一個向量使用你的數組,並且索引值不是重要。但是如果你有一個你想旋轉的關聯數組,這個方法會破壞你的數組鍵。看到我的答案,以保存它們的方式。 – 2011-10-26 22:47:41

+0

@Cam,你說得對,即使OP沒有提到數組索引,只是數值。對於那些正在尋找解決方案來旋轉數組元素的兩部分的人來說,您的答案很有價值。 (+1爲你的答案) – Wh1T3h4Ck5 2011-10-29 06:46:34

+0

是的,顯然你的方法已經足夠了OP,否則他不會接受它!但是,是的,以爲我會添加我的答案,以防止任何人遇到同樣的問題,我做了:) – 2011-10-30 07:44:19

1

邏輯是交換元素。算法可能看起來像 -

for i = 0 to arrayLength - 1 
    swap(array[i], array[i+1])  // Now array[i] has array[i+1] value and 
            // array[i+1] has array[i] value. 
+0

@Dylan - 如果你想爲自己寫一個,可以實現上面的邏輯。 – Mahesh 2011-04-08 23:31:26

0

號檢查文檔array_shift及其相關功能的一些工具可以用來寫一個。該頁面的評論中甚至可能會實現一個array_rotate函數。

爲了全面瞭解PHP中可用的數組函數,還需要閱讀左側邊欄列出的數組函數。

3

這很簡單,可以用很多方式完成。例如:

$array = array('a', 'b', 'c'); 
$array[] = array_shift($array); 
1

保持鍵和旋轉的方法。使用相同的概念,作爲array_push(數組,array_shift(陣列)),相反,我們將使用array_merge的2個array_slices

$x = array("a" => 1, "b" => 2, "c" => 3, 'd' => 4);

到第一元件移動到結束

array_merge(array_slice($x, 1, NULL, true), array_slice($x, 0, 1, true) //'b'=>2, 'c'=>3, 'd'=>4, 'a'=>1

要最後一個元素移動到前面

array_merge(array_slice($x, count($x) -1, 1, true), array_slice($x, 0, //'d'=>4, 'a'=>1, 'b'=>2, 'c'=>3

0
$daynamesArray = array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"); 
array_push($daynamesArray, array_shift($daynamesArray)); //shift by one 
array_push($daynamesArray, array_shift($daynamesArray)); //shift by two 
print_r($daynamesArray); 

輸出開始於 「星期三」:

Array ([0] => Wednesday [1] => Thursday [2] => Friday [3] => Saturday [4] => Sunday [5] => Monday [6] => Tuesday 
1

您可以使用此功能:

function arr_rotate(&$array,$rotate_count) { 
     for ($i = 0; $i < $rotate_count; $i++) { 
      array_push($array, array_shift($array)); 
     } 
    } 

用法:

$xarr = array('1','2','3','4','5'); 
    arr_rotate($xarr, 2); 
    print_r($xarr); 

結果:

Array ([0] => 3 [1] => 4 [2] => 5 [3] => 1 [4] => 2) 
+0

不錯的簡潔功能,但我覺得它可以通過確保您沒有循環遍歷數次以上的元素來稍微改進。例如'arr_rotate($ xarr,count($ xarr));'將以相同的順序得到結果。添加'$ rotate_count%= count($ array)'這一行將確保迭代的最大次數總是小於元素的數量。 – 2018-03-02 06:49:30

0

有一個關於Hackerrank陣列旋轉任務:https://www.hackerrank.com/challenges/array-left-rotation/problem

並且array_pusharray_shift的提議解決方案將適用於除最後一個測試案例(由於超時而失敗)之外的所有測試案例。所以,array_pusharray_shift會給你不是最快的解決方案。

下面是更快的方法:

function leftRotation(array $array, $n) { 
    for ($i = 0; $i < $n; $i++) { 
     $value = array[$i]; unset(array[$i]); array[] = $value; 
    } 
    return array; 
} 
0

通過數組循環和shift -ing和push -ing,可旋轉陣列一種常見的方式,但它可以經常搞砸你的鑰匙。更穩健的方法是使用array_mergearray_splice的組合。

/** 
* Rotates an array. 
* 
* Numerical indexes will be renumbered automatically. 
* Associations will be kept for keys which are strings. 
* 
* Rotations will always occur similar to shift and push, 
* where the number of items denoted by the distance are 
* removed from the start of the array and are appended. 
* 
* Negative distances work in reverse, and are similar to 
* pop and unshift instead. 
* 
* Distance magnitudes greater than the length of the array 
* can be interpreted as rotating an array more than a full 
* rotation. This will be reduced to calculate the remaining 
* rotation after all full rotations. 
* 
* @param array $array The original array to rotate. 
* Passing a reference may cause the original array to be truncated. 
* @param int $distance The number of elements to move to the end. 
* Distance is automatically interpreted as an integer. 
* @return array The modified array. 
*/ 
function array_rotate($array, $distance = 1) { 
    settype($array, 'array'); 
    $distance %= count($array); 
    return array_merge(
     array_splice($array, $distance), // Last elements - moved to the start 
     $array       // First elements - appended to the end 
    ); 
} 
// Example rotating an array 180°. 
$rotated_180 = array_rotate($array, count($array)/2); 

另外,如果您還發現需要讓他們有不同的價值觀匹配旋轉鍵,可以結合array_keysarray_combinearray_rotatearray_values

/** 
* Rotates the keys of an array while keeping values in the same order. 
* 
* @see array_rotate(); for function arguments and output. 
*/ 
function array_rotate_key($array, $distance = 1) { 
    $keys = array_keys((array)$array); 
    return array_combine(
     array_rotate($keys, $distance), // Rotated keys 
     array_values((array)$array) // Values 
    ); 
} 

或可替代地旋轉的值,同時保持以相同的順序的鍵(等效於調用該匹配array_rotate_key函數調用負距離)。

/** 
* Rotates the values of an array while keeping keys in the same order. 
* 
* @see array_rotate(); for function arguments and output. 
*/ 
function array_rotate_value($array, $distance = 1) { 
    $values = array_values((array)$array); 
    return array_combine(
     array_keys((array)$array),  // Keys 
     array_rotate($values, $distance) // Rotated values 
    ); 
} 

最後,如果你想防止重新編號的數字指標。

/** 
* Rotates an array while keeping all key and value association. 
* 
* @see array_rotate(); for function arguments and output. 
*/ 
function array_rotate_assoc($array, $distance = 1) { 
    $keys = array_keys((array)$array); 
    $values = array_values((array)$array); 
    return array_combine(
     array_rotate($keys, $distance), // Rotated keys 
     array_rotate($values, $distance) // Rotated values 
    ); 
} 

這可能是有益的,執行一些基準測試,但是,我希望每個請求轉一小撮不會影響性能顯着,無論採用哪種方法。

也應該可以通過使用自定義排序功能來旋轉數組,但它很可能過於複雜。即usort