一道小題


1
2
3
4
5
6
7
8
9
10
11
12
有一個 Array 如下

$dict = ['a' , 'b' , 'c' , 'd' , 'e' ];

目前有一個變數 $i 控制想輸出的 Array

當 $i = a 時回傳 abcde
當 $i = b 時回傳 bcdea
當 $i = d 時回傳 deabc

怎麼寫比較漂亮?
想知道是否就只能用迴圈跑?

想到的解法如下

方法一 (直覺.但很多計算)

  1. 取出目前 $i 值的位置
  2. 取兩種 array (1. 由這位置取到尾, 2.再取 0 到這值置)
  3. 最後將這兩種合起來
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
$dict = ['a' , 'b' , 'c' , 'd' , 'e'];

$position = array_search('c', $dict);
$totalSize = count($dict);
$findOut = array_slice($dict, $position, $totalSize);
$findOutSize = count($findOut);

if ($findOutSize < $totalSize) {
$appendSize = $totalSize - $findOutSize;
$appendDict = array_slice($dict, 0, $appendSize);
}else{
$appendDict = [];
}

print_r(array_merge($findOut, $appendDict));

方法二 (用遞歸.不算直覺.但快很多)

1
2
3
4
5
6
7
8
9
10
<?php
function genResult(array $dict, $startChar) {
if ($dict[0] === $startChar) return $dict;

array_push($dict, array_shift($dict));

return genResult($dict, $startChar);
}

print_r(genResult(['a' , 'b' , 'c' , 'd' , 'e'], 'c'));