简体   繁体   English

PHP通过条件循环遍历数组

[英]PHP loop through array with condition

I have a loop which i made like this: 我有这样一个循环:

$arr = array(1, 2, 3, 4, 5, 6, 7);
foreach ($arr as &$value) {
    echo $value;
}

My loop result shows this: 我的循环结果显示了这一点:

1234567

I would like this to only show the numbers 1 to 4. And when it reaches 4 it should add a break and continue with 5671. 我只想显示数字1到4。当数字达到4时,应该加一个中断,然后继续5671。

So an example is: 因此,一个示例是:

1234<br>
5671<br>
2345<br>
6712<br>

I have to make this but I have no idea where to start, all hints/tips are very welcome or comment any direction I should Google. 我必须这样做,但是我不知道从哪里开始,非常欢迎所有提示/提示,也没有评论我应该使用Google的任何方向。

This produces the exact results you want 这将产生您想要的确切结果

$arr = array(1, 2, 3, 4, 5, 6, 7);
$k=0;
for($i=1;$i<=5;++$i){
  foreach ($arr as &$value) {
    ++$k;
     echo $value;
     if($k %4 == 0) {
    echo '<br />';
   $k=0;
}
}
}

Here is more universal function- you can pass an array as argument, and amount of elements you want to display. 这是更通用的功能-您可以传递数组作为参数,以及要显示的元素数量。

<?php

$array = array(1,2,3,4,5,6,7);

function getFirstValues(&$array, $amount){
    for($i=0; $i<$amount; $i++){
        echo $array[0];
        array_push($array, array_shift($array));
    }
    echo "<br />";
}

getFirstValues($array, 4);
getFirstValues($array, 4);
getFirstValues($array, 4);
getFirstValues($array, 4);


?>

The result is: 结果是:
1234 1234
5671 5671
2345 2345
6712 6712

You are looking for array_chunk() 您正在寻找array_chunk()

$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
$chunks = array_chunk($arr, 4);
foreach ($chunks as $array) {
    foreach ($array as $value) {
        echo $value;
    }
    echo "<br />";
}

The output is: 输出为:

1234
5678
9101112
13

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM