将数组拆分为 10 个元素的组

问题描述 投票:0回答:4

我有一个包含 40 个元素的数组。我只需要从数组中显示第一组 10 个元素,然后在表中显示一些静态行。显示该静态行后,我只想显示另一组 10 行。同样,我需要显示所有 40 个元素。

php arrays
4个回答
3
投票

你可以试试

$array = range(1,40);
foreach (array_chunk($array, 10) as $current)
{
    foreach($current as $data)
    {
        // Display your Information
    }
}

3
投票

0
投票

使用
array_slice()

它返回由偏移量和长度参数指定的数组数组中的元素序列。

示例:

<?php
    $myArray = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40);
    print_r(array_slice($myArray, 0, 10));
    print_r(array_slice($myArray, 10, 10));
    print_r(array_slice($myArray, 20, 10));
    print_r(array_slice($myArray, 30, 10));
?>

输出:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 10
)
Array
(
    [0] => 11
    [1] => 12
    [2] => 13
    [3] => 14
    [4] => 15
    [5] => 16
    [6] => 17
    [7] => 18
    [8] => 19
    [9] => 20
)
Array
(
    [0] => 21
    [1] => 22
    [2] => 23
    [3] => 24
    [4] => 25
    [5] => 26
    [6] => 27
    [7] => 28
    [8] => 29
    [9] => 30
)
Array
(
    [0] => 31
    [1] => 32
    [2] => 33
    [3] => 34
    [4] => 35
    [5] => 36
    [6] => 37
    [7] => 38
    [8] => 39
    [9] => 40
)

小提琴:http://codepad.viper-7.com/mfzof6


0
投票

最有效的方法是使用 modulus 运算符,如下所示:

$tot = count($array);
for($i=0;$i<$tot;$i++) {
   echo $array[$i] . '<br>';
   if(($i+1) % 10 == 0) {
      echo '--- TEN GROUP --- <br>';
   }
}

输出示例:

text_1
text_2
...
text_9
text_10
--- TEN GROUP --- 
text_11
text_12
...
text_19
text_20
--- TEN GROUP --- 
text_21
text_22
...
© www.soinside.com 2019 - 2024. All rights reserved.