在php中一次迭代一次数组n次

时间:2014-02-26 07:25:53

标签: php arrays

我有一个包含12个元素的数组,我需要一次显示4个项目。这就是我所拥有的

<?php

$array = Array
(
    0 => "ed",
    1 => "smith.co.uk",
    2 => "http://edsmith.co.uk/smith.jpg",
    3 => "Published",
    4 => "ford attenborough",
    5 => "ford.co.uk",
    6 => "http://fordattenborough.co.uk/ford.jpg",
    7 => "Pending Approval",
    8 => "greg tolkenworth",
    9 => "greg.co.uk",
    10 => "http://greg.co.uk/greg.jpg",
    11 => "In Future"
);
foreach($array as $key => $value){
echo $value."---".$value."---".$value."---".$value."<br/><hr/>";
}
?>

我需要一次显示数组4的值,或一次显示3

4 个答案:

答案 0 :(得分:2)

您可以使用array_splice()。 请参阅以下示例:

<?php
$array = Array
(
    0 => "ed",
    1 => "smith.co.uk",
    2 => "http://edsmith.co.uk/smith.jpg",
    3 => "Published",
    4 => "ford attenborough",
    5 => "ford.co.uk",
    6 => "http://fordattenborough.co.uk/ford.jpg",
    7 => "Pending Approval",
    8 => "greg tolkenworth",
    9 => "greg.co.uk",
    10 => "http://greg.co.uk/greg.jpg",
    11 => "In Future"
);

while(!empty($array)) {
    $partial = array_splice($array, $i, 4);
    print_r($partial);
}

Here是执行的示例。

答案 1 :(得分:1)

<?php

$array = Array
(
    0 => "ed",
    1 => "smith.co.uk",
    2 => "http://edsmith.co.uk/smith.jpg",
    3 => "Published",
    4 => "ford attenborough",
    5 => "ford.co.uk",
    6 => "http://fordattenborough.co.uk/ford.jpg",
    7 => "Pending Approval",
    8 => "greg tolkenworth",
    9 => "greg.co.uk",
    10 => "http://greg.co.uk/greg.jpg",
    11 => "In Future"
);
$i=0;
while($i < count($array)) { 
    echo $array[$i]."---".$array[$i+1]."---".$array[$i+2]."---".$array[$i+3]."<br/><hr/>";
    $i+=4;
  }  
?>

答案 2 :(得分:0)

拆分数组

$newarray = array_chunk($array, 4);

现在$newarray包含数组,每个数组包含4个项目。像这样,

$newarray = Array(
  0 => Array( 
    0 => "ed",
    1 => "smith.co.uk",
    2 => "http://edsmith.co.uk/smith.jpg",
    3 => "Published"
   ),
  1 => Array(
    0 => "ford attenborough",
    1 => "ford.co.uk",
    2 => "http://fordattenborough.co.uk/ford.jpg",
    3 => "Pending Approval"
   ),
 2 => Array(
    0 => "greg tolkenworth",
    1 => "greg.co.uk",
    2 => "http://greg.co.uk/greg.jpg",
    3 => "In Future"
   )
);

现在,您可以在foreach上运行$newarray,一次打印4个项目。

foreach($newarray as $arr){
  foreach($arr as $a){
   echo $a;
  }
}

答案 3 :(得分:0)

下面是一些棘手但有效的代码

$array = Array
(
    0 => "ed",
    1 => "smith.co.uk",
    2 => "http://edsmith.co.uk/smith.jpg",
    3 => "Published",
    4 => "ford attenborough",
    5 => "ford.co.uk",
    6 => "http://fordattenborough.co.uk/ford.jpg",
    7 => "Pending Approval",
    8 => "greg tolkenworth",
    9 => "greg.co.uk",
    10 => "http://greg.co.uk/greg.jpg",
    11 => "In Future"
);
$val = "";
foreach($array as $key => $value){
            if($key > 0 && $key <= 3){
        continue;
    }
        $val .= $value . " =|= ";

    if(($key+1) % 4 == 0){
        echo $val."<br/><hr/>";
        $val = "";
    }
}