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条)

报告相同问题?