如何在PHP中获取子数组?

49

我想获得由原始数组$arr的前4行组成的数组,

在PHP中如何实现?

3个回答

92

如果我不知道偏移量呢? - jlcharette
@JCharette - 然后您需要识别偏移量,使用像 array_search() 这样的函数......但这完全取决于您需要做什么,并且是一个完全不同的问题。 - Mark Baker

18

你需要使用 array_slice()

$output = array_slice($arr, 0, 4);

8

看这个...应该会有所帮助

<?php
$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));
?>

来自http://docs.php.net/array_slice


当您发布来自其他来源的代码时,应始终同时粘贴链接。 - Andy E

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接