2016-11-28 27 views
1

比方说,我有此数组:PHP圆形环至n-1元素

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

我有开始指示符,$startpos,其可能值可以从0到myArray的号码的任何值的元素。

所以,如果$startpos = 0,所需的打印结果将是a, b, c, d, e, f, g

如果$startpos = 2,所需的打印结果将是c, d, e, f, g, a, b

如果$startpos = 5,所需的打印结果将是f, g, a, b, c, d, e

我已经一直在寻找通过SO(类似的问题在Treat an array as circular array when selecting elements - PHP)的内置或自定义功能,并看看http://www.w3schools.com/php/php_ref_array.asp,但我没有得到预期的结果。任何人都可以请给我一个建议?

回答

4

你可以使用array_slice功能与array_merge功能如下:

$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 A B C

$ startpos:0

O/P:A B C d E F G