PHP-按索引范围获取数组记录
你好 是否有任何PHP本机函数根据索引的开始和结束返回数组中的记录范围 i、 e: 现在我只想返回索引1和3(b,c,d)之间的记录PHP-按索引范围获取数组记录,php,arrays,Php,Arrays,你好 是否有任何PHP本机函数根据索引的开始和结束返回数组中的记录范围 i、 e: 现在我只想返回索引1和3(b,c,d)之间的记录 有什么想法吗?你不能用例如 我们有一项任务 array数组\u切片(array$array,int$offset[,int$length[,bool$preserve\u keys=false]) 例如: $input = array("a", "b", "c", "d", "e"); $output = array_slice($input, 2);
有什么想法吗?你不能用例如 我们有一项任务
array数组\u切片(array$array,int$offset[,int$length[,bool$preserve\u keys=false])
例如:
$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));
$input=数组(“a”、“b”、“c”、“d”、“e”);
$output=array_slice($input,2);//返回“c”、“d”和“e”
$output=array_slice($input,-2,1);//返回“d”
$output=array_slice($input,0,3);//返回“a”、“b”和“c”
//请注意数组键中的差异
打印(数组切片($input,2,-1));
打印(数组切片($input,2,-1,true));
$array1=数组(1,2,3,4,5,6,23,24,26,21,12);
foreach(范围($array1[0],$array1[5])为$age){
回声“年龄:{$Age}
”;
}
您应该获得以下输出:
年龄:1
年龄:2
年龄:3
年龄:4
年龄:5
年龄:6岁
这个问题与“PHP数组_切片”下表决同义。这是一个低质量的答案,在非连续的情况下无法移植。在这里,您可以看到,当数组值中存在间隙时,您的方法会严重失败
range()
在数组中没有值的地方生成值。以下是您自己输入的缺陷:请删除此答案array\u slice()
和array\u intersect\u key()
是最明智的方法。
$a = array(0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd');
array_slice($a, 1, 3);
$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));
$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 />";
}
$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 )