0

例如我有一个数组:

$array = array(25, 50, 75, 100); // I get an array of some numbers
$position = 50; // I get some value to start with
$limit = 3; // I need to fill another array with 3 next values from the starting position

现在我需要使用什么代码来填充一个新数组,就像这样:

$new_array = array(75, 100, 25); // the start position is 50, but I need the next 3

有任何想法吗??

4

3 回答 3

2

您可以使用array_search来查找关键字在数组中的位置。% 算术运算符,用于在到达结束后转到第一个元素。休息是你的逻辑。

<?php
    $array = array(25, 50, 75, 100);
    $position = 10;
    $limit = sizeof($array)-1;

    $pos = array_search($position, $array);;

    if(!($pos === false))
    {
        for($i=0;$i<$limit;$i++)
        {
            $pos = (($pos+1)%sizeof($array));
            echo $array[$pos]."<br>";
        }
    }
    else
    {
        echo "Not Found";
    }
?>
于 2012-10-26T23:21:42.480 回答
2

我喜欢有抽象逻辑的函数。所以我建议写一个函数,它接受数组、开始的位置和限制:

<?php
function loop_array($array,$position,$limit) {

    //find the starting position...
    $key_to_start_with = array_search($position, $array);
    $results = array();

    //if you couldn't find the position in the array - return null
    if ($key_to_start_with === false) {
        return null;
    } else {
            //else set the index to the found key and start looping the array
        $index = $key_to_start_with;
        for($i = 0; $i<$limit; $i++) {
                    //if you're at the end, start from the beginning again
            if(!isset($array[$index])) {
                $index = 0;
            }
            $results[] = $array[$index];
            $index++;
        }
    }
    return $results;
}

因此,现在您可以使用所需的任何值调用该函数,例如:

$array = array(25, 50, 75, 100);
$position = 75;
$limit = 3;

$results = loop_array($array,$position,$limit);

if($results != null) {
    print_r($results);
} else {
    echo "The array doesn't contain '{$position}'";
}

输出

Array
(
    [0] => 75
    [1] => 100
    [2] => 25
)

或者你可以用任何其他值循环它:

$results = loop_array(array(1,2,3,4,5), 4, 5);

这是一个工作示例:http ://codepad.org/lji1D84J

于 2012-10-26T23:39:18.500 回答
1

您可以使用array_slice()array_merge()来实现您的目标。

假设你知道 50 的位置是 2。

那么你可以通过 -

array_slice(array_merge(array_slice($array, 2), array_slice($array, 0, 2)), 3);

基本上,您从起始位置获得两个子数组,连接在一起,然后删除拖尾部分。

于 2012-10-26T23:24:51.980 回答