使用基数组从范围元素创建数组

时间:2014-12-07 09:02:16

标签: php arrays

我有一个像这样的数组

$baseArray = array( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 );

所以我想制作两个范围

的数组
$arrayOne = from index 5 - 10
$arrayTwo = from index 15 - 20

如何拆分$ baseArray以在php中创建类似的数组?

3 个答案:

答案 0 :(得分:2)

有功能array_slice

$baseArray = array( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 );
$arrayOne = array_slice($baseArray, 5, 10);
$arrayTwo = array_slice($baseArray, 15, 20);

答案 1 :(得分:0)

这应该适合你:

(仅当您的数字索引以0开头时才有效

$baseArray = array( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 );
$arrayOne = array();
$arrayTwo = array();

foreach($baseArray as $k => $v) {

    if($k >= 5 && $k <= 10)
        $arrayOne[] = $v;
    elseif($k >= 15 && $k <= 20)
        $arrayTwo[] = $v;

}

print_r($arrayOne);
print_r($arrayTwo);

输出:

arrayOne:

Array
(
    [0] => 6
    [1] => 7
    [2] => 8
    [3] => 9
    [4] => 10
    [5] => 11
)

arrayTwo:

Array
(
    [0] => 16
    [1] => 17
    [2] => 18
    [3] => 19
    [4] => 20
)

答案 2 :(得分:0)

可以尝试使用for()&amp; array_slice()。例如:

$baseArray = array( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 );
$newAr = array();
for($i = 5; $i < count($baseArray); $i += 10){
    $newAr[] = array_slice($baseArray, $i, 5);
}
print '<pre>';
print_r($newAr);
print '</pre>';