简体   繁体   English

在x次之后,Foreach会做什么?

[英]Foreach do something after x times?

I'm trying to create an automatic block with links [ They come from an array ], everything went well before I had too much links, Now they're all on the same line, How can I make foreach print br after 4 times? 我正在尝试创建一个带有链接的自动块[它们来自数组],在链接太多之前一切进展顺利,现在它们都在同一行上,如何在4次打印后进行foreach打印?

now it's like this: 现在是这样的:

foreach($this->rpanelinks as $name => $url) {
    echo '<a href="' . BASE_URL . $url . '">' . $name . '</a>';
}

Thanks! 谢谢!

Use a counter: 使用计数器:

$i = 1;

foreach($this->rpanelinks as $name => $url) {
    if($i == 4) 
        echo '<br>';

    echo '<a href="' . BASE_URL . $url . '">' . $name . '</a>';

    ++$i;
}

or if you wan't every 4 times 或者如果您不想 4次

$i = 1;

foreach($this->rpanelinks as $name => $url) {
    if($i % 4 == 0) 
         echo '<br>';

    echo '<a href="' . BASE_URL . $url . '">' . $name . '</a>';

    ++$i;
}

$i % 4 calculates the rest of the operation $i / 4 and if it's 0 the value uf $i is dividable by 4 . $i % 4计算其余的操作$i / 4 ,如果它为0则uf $i的值可除以4

I don't understand the question much to be honest. 老实说,我对这个问题不太了解。 However, you can put whatever logic to your foreach you want. 但是,您可以将任何逻辑添加到所需的foreach中。 For example: 例如:

$counter = 0;
foreach($this->rpanelinks as $name => $url) {
    $counter ++;
    echo '<a href="' . BASE_URL . $url . '">' . $name . '</a>';
    if ($counter %4 == 0) echo '<br />';
}
$i = 0;

foreach($this->rpanelinks as $name => $url) {
    ++$i;
    if($i >= 4){
        echo '<br/>';
        $i=0;
    }
    echo '<a href="' . BASE_URL . $url . '">' . $name . '</a>';

}

use variable to count your links, following code prints breakline after each 4 links 使用变量来计算您的链接,下面的代码在每4个链接后会打印breakline

$counter = 0;
foreach($this->rpanelinks as $name => $url) {
    echo '<a href="' . BASE_URL . $url . '">' . $name . '</a>';
    if(++$counter % 4 == 0) {
        echo '<br />';
    }
}

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

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