开发者

PHP - get array records by index range

HI there,

Is there any PHP native function which returns the range of records from the array based on the start and end of the index?

i.e.:

array(0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd');

and now I would like to开发者_Python百科 only return records between index 1 and 3 (b, c, d).

Any idea?


Couldn't you do that with e.g. array_slice?

$a = array(0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd');
array_slice($a, 1, 3); 


there is a task for array_slice

array array_slice ( array $array , int $offset [, int $length [, bool $preserve_keys = false ]] )

example:

$input = array("a", "b", "c", "d", "e");

$output = array_slice($input, 2);      // returns "c", "d", and "e"
$output = array_slice($input, -2, 1);  // returns "d"
$output = array_slice($input, 0, 3);   // returns "a", "b", and "c"

// note the differences in the array keys
print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));


By using array_intersect_key

$myArray = array(0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd');
$arrayRange = array('1', '2', '3');

// this can also be used if you have integer only array values
// $arrayRange = range(1,3); 

$newArray = array_intersect_key($myArray, array_flip($arrayRange));

print_r($newArray);  // output: Array ( [1] => b [2] => c [3] => d )


$array1 = array(1,2,3,4,5,6,23,24,26,21,12);

    foreach(range ($array1[0],$array1[5]) as $age){
        echo "Age: {$age}<br />";
    }

you should get the following output:

Age: 1

Age: 2

Age: 3

Age: 4

Age: 5

Age: 6

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜