PHP - 按索引范围获取数组记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4715555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 14:07:08  来源:igfitidea点击:

PHP - get array records by index range

phparrays

提问by user398341

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?

是否有任何 PHP 本机函数根据索引的开始和结束返回数组中的记录范围?

i.e.:

IE:

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

and now I would like to only return records between index 1 and 3 (b, c, d).

现在我只想返回索引 1 和 3 (b, c, d) 之间的记录。

Any idea?

任何的想法?

回答by polarblau

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

你不能用 eg 做到这一点array_slice吗?

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

回答by bensiu

there is a task for array_slice

array_slice有一个任务

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

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 Mukesh Chapagain

By using array_intersect_key

通过使用 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 )

回答by Kaiser

$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

年龄:1

Age: 2

年龄:2

Age: 3

年龄:3

Age: 4

年龄:4

Age: 5

年龄:5

Age: 6

年龄:6