Helper.php 1.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. <?php
  2. namespace App\Http\Helper;
  3. class Helper {
  4. /**
  5. * Summary of findNextStepsIDs
  6. * @param array $arr 目標陣列
  7. * @param mixed $targetID 指定的value
  8. * @param mixed $count 尋找組數
  9. * @return array
  10. */
  11. function findArrayTargetIndex(array $arr, $target, mixed $count) {
  12. // 找到指定value 的Index
  13. $targetIndex = array_search($target, $arr);
  14. $indexCount = count($arr);
  15. // 如果指定的value不存在陣列中,則回傳空陣列
  16. if ($targetIndex === false) {
  17. return [];
  18. }
  19. $result = [];
  20. //列出總共想找的序列Index, 正數為後 N 篇 , 負數為前 N 篇
  21. $loopCount = is_array($count) ? $count : [$count];
  22. foreach($loopCount as $num){
  23. for($i = 1; $i <= abs($num); $i++){
  24. //假設如果往 前/後 已經沒有的話就走循環
  25. if($num < 0){
  26. $result[] = isset($arr[$targetIndex - $i]) ? $arr[$targetIndex - $i] : $arr[$targetIndex - $i + $indexCount];
  27. }else{
  28. $result[] = isset($arr[$targetIndex + $i]) ? $arr[$targetIndex + $i] : $arr[$targetIndex + $i - $indexCount];
  29. }
  30. }
  31. }
  32. return $result;
  33. }
  34. }