doupa2871 2014-04-26 04:11 采纳率: 100%
浏览 79
已采纳

玩Modulus Division

I'm trying out the modulus division with a foreach loop, and I'm having a bit trouble understanding it.

$counter = 0;
foreach($result as $row){
    if(isset($row['username'])){
        if (($counter) % 2 == 0){
            echo "<tr class=\"r1\"><td class=\"center\"><a href=\"profile.php?username=" . $row['username'] . "\">" . $row['username'] . "</a></td></tr>";
        }
        else{
            echo "<tr class=\"r0\"><td class=\"center\"><a href=\"profile.php?username=" . $row['username'] . "\">" . $row['username'] . "</a></td></tr>";
        }
        $counter++;
    }
}

I want to output:

<tr class="r0">
    <td><a href="profile.php?username=Bob">Bob</a></td>
    <td><a href="profile.php?username=Daniel">Daniel</a></td>
</tr>
<tr class="r1">
    <td><a href="profile.php?username=Dylan">Dylan</a></td>
    <td><a href="profile.php?username=Bruce">Bruce</a></td>
</tr>

But currently, with my loop, I'm outputting:

<tr class="r1">
    <td<a href="profile.php?username=Bob">Bob</a></td>
</tr>
<tr class="r0">
    <td><a href="profile.php?username=Daniel">Daniel</a></td>
</tr>
<tr class="r1">
    <td><a href="profile.php?username=Dylan">Dylan</a></td>
</tr>
<tr class="r0">
    <td><a href="profile.php?username=Bruce">Bruce</a></td>
</tr>

Can someone explain to me exactly how modulus division works? Thank you.

  • 写回答

2条回答 默认 最新

  • dtt27783 2014-04-26 15:02
    关注

    I got this to work. My problem was that my array was multidimensional, so I converted it to a single array. Afterwards, I used array_chunks.

    $chunks = array_chunk($l, 2);
    $i=0;
    foreach($chunks as $mychunk){
    if($i%2== 0){
        echo "<tr class=\"r0\">";
    } else { echo "<tr class=\"r1\">"; }
    $i++;
        foreach($mychunk as $newchunk) 
        {
        echo "<td class=\"center\"><a href=\"profile.php?username=" . $newchunk . "\">" . $newchunk . "</a></td>";
        }
    
        echo "</tr>";
    }
    

    For anyone looking to convert multidimensional arrays into single dimensional array:

    function array_flatten($array) { 
      if (!is_array($array)) { 
        return FALSE; 
      } 
      $result = array(); 
      foreach ($array as $key => $value) { 
        if (is_array($value)) { 
          $result = array_merge($result, array_flatten($value)); 
        } 
        else { 
          $result[$key] = $value; 
        } 
      } 
      return $result; 
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 根据以下文字信息,做EA模型图
  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥60 关机时蓝屏并显示KMODE_EXCEPTION_NOT_HANDLED,怎么修?
  • ¥66 如何制作支付宝扫码跳转到发红包界面