2016-11-28 6 views
1

に配列を通してのは、私は、この配列があるとしましょう:PHP円形ループのnからn-1の要素

$myArray = array(a, b, c, d, e, f, g); 

をそして、私はその可能値が0からMyArrayというの番号に任意の値にすることができ、開始インジケータ、$startposを、持っています要素の

$startpos = 0場合$startpos = 2場合、所望の印刷結果がa, b, c, d, e, f, g

だろう$startpos = 5場合、所望の印刷結果がc, d, e, f, g, a, b

だろうだから、所望の印刷結果は、私がしましたf, g, a, b, c, d, e

だろうSO(類似の質問Treat an array as circular array when selecting elements - PHP)を使用してPHPの組み込み関数またはカスタム関数を検索していましたが、http://www.w3schools.com/php/php_ref_array.aspのように見えましたが、目的の結果が得られません。誰でも私に提案をお願いできますか?

答えて

4

次のようarray_merge機能をarray_slice機能を使用することができます。

$myArray = array('a', 'b', 'c', 'd', 'e', 'f', 'g'); 
$startpos = 2; 


$output = array_merge(
       array_slice($myArray,$startpos), 
       array_slice($myArray, 0, $startpos) 
        ); 
var_dump($output); 

出力:

array(7) { 
    [0]=> 
    string(1) "c" 
    [1]=> 
    string(1) "d" 
    [2]=> 
    string(1) "e" 
    [3]=> 
    string(1) "f" 
    [4]=> 
    string(1) "g" 
    [5]=> 
    string(1) "a" 
    [6]=> 
    string(1) "b" 
} 
+1

は、バディをありがとう;) – b1919676

1

demo

<?php 
     $myArray = array(a, b, c, d, e, f, g); 
     $startpos = 3; 
     $o = f($myArray, $startpos); 
     echo json_encode($o); 

     function f($myArray, $startpos) 
     { 
     $o = array(); 
     $l = count($myArray); 
     array_walk($myArray, function($v, $k) use(&$o, $l, $startpos) 
     { 
      $o[($k + $l - $startpos) % $l] = $v; 
     }); 
     ksort($o); 
     return ($o); 
     } 

またはforeachのメソッドを使用します。 demo

<?php 
    $myArray = array(a, b, c, d, e, f, g); 
    $startpos = 3; 
    echo json_encode(f($myArray, $startpos)); 

    function f($myArray, $startpos) 
    { 
    $o = array(); 
    $l = count($myArray); 
    foreach($myArray as $k => $v) 
    { 
     $o[($k + $l - $startpos) % $l] = $v; 
    } 
    ksort($o); 
    return $o; 
    } 

outpur:["d","e","f","g","a","b","c"]

+0

、あまりにもクリスありがとうございました。 – b1919676

+0

@ b1919676私の喜び –

0

あなたは、単純なロジックを探している場合は、以下のcodepieceのために行くことができます。

$myArray = array('a', 'b', 'c', 'd', 'e', 'f', 'g'); 
$startpos = <any_position>; 
$dummy_startpos = $startpos; //keeping safe startpos for circular calculation 
$initialpos = 0; 

//loop to print element from startpos to end 
while($dummy_startpos < count($myArray)) 
{ 
    echo $myArray[$dummy_startpos] . ' '; 
    $dummy_startpos++; 
} 

//if startpos is not initial position 
//start from first and print element till startpos 
if($startpos > 0) 
{ 
    while($elementleft < $startpos) 
    { 
     echo $myArray[$elementleft] . ' '; 
     $elementleft++; 
    } 
} 

出力:

$ startpos:3

O/P:D E F G、BのC

$ startpos:0

O/P:BのC D EがF gの

関連する問題