php数组和for循环 - 在5个结果后添加<br/>

时间:2016-07-30 01:55:13

标签: php arrays

这是我的代码:

$sm2 = array( "angry", "cool", "cry", "happy", "heart", "kiss", "mute", "sad", "smile"); 

for($j=0;$j<count($sm2); $j++) {
    $data=$data . "<img id='". $sm2[$j] ."' src='images/emotions/" . $sm2[$j] . ".png' data-toggle='tooltip' title=". $sm2[$j] ."  width='32' height='32' style='margin:5px;'
    onclick='insertEmoticons(this.id);'/>";
}

如何在5个结果后插入<br>代码,因为我不希望所有内容都在一行上。

2 个答案:

答案 0 :(得分:2)

使用Modulus operator

<?php
$sm2 = array( "angry", "cool", "cry", "happy", "heart", "kiss", "mute", "sad", "smile"); 
for($j=0;$j<count($sm2); $j++) {
     if(!empty($j) && $j % 5 == 0) {
          echo '<br>';
     }
     echo $sm2[$j];
}

输出:

angrycoolcryhappyheart<br>kissmutesadsmile

演示:https://eval.in/614166

或使用您的实际代码:

for($j=0;$j<count($sm2); $j++) {
    if(!empty($j) && $j % 5 == 0) {
          $data .= '<br>';
    }
    $data=$data . "<img id='". $sm2[$j] ."' src='images/emotions/" . $sm2[$j] . ".png' data-toggle='tooltip' title=". $sm2[$j] ."  width='32' height='32' style='margin:5px;'
    onclick='insertEmoticons(this.id);'/>";
}

另请注意,$data=$data .$data .= ...相同。

答案 1 :(得分:0)

$sm2 = array( "angry", "cool", "cry", "happy", "heart", "kiss", "mute", "sad", "smile"); 

for($j=0;$j<count($sm2); $j++) {
    $data=$data . "<img id='". $sm2[$j] ."' src='images/emotions/" . $sm2[$j] . ".png' data-toggle='tooltip' title=". $sm2[$j] ."  width='32' height='32' style='margin:5px;' onclick='insertEmoticons(this.id);'/>";
    if ( (($j+1) % 5) == 0)
    {
        $data = $data . "<br>";
    }

}