玩Modulus Division

时间:2014-04-26 04:11:14

标签: php loops foreach division modulus

我尝试使用foreach循环进行模数除法,并且我对它的理解有点麻烦。

$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++;
    }
}

我想输出:

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

但是目前,通过我的循环,我输出了:

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

有人可以向我解释模数除法的工作原理吗?谢谢。

2 个答案:

答案 0 :(得分:1)

在这里,您希望在一行中显示两条记录。实际上,模数除法将返回除法的余数。试试:

$counter = 0;
$i=1;
foreach($result as $row){
    if(isset($row['username'])){
        if (($counter) % 2 == 0){  // that is the counter value/2 doesnot returns a remainder ie, divisible by 2, then create another row
         if($i%2==0)
         {
           echo "<tr class=\"r1\">";  
         }
         else
         {
            echo "<tr class=\"r0\">";  
         }
        }
        else{
            echo "<td class=\"center\"><a href=\"profile.php?username=" . $row['username'] . "\">" . $row['username'] . "</a></td>";
        }
        if (($counter) % 2 == 0){     // close the tr if the counter doesnot return remainder
            echo "</tr>";
        }
        $counter++;
        $i++;
    }
}

答案 1 :(得分:0)

我让这个工作。我的问题是我的数组是多维的,所以我将它转换为单个数组。之后,我使用了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>";
}

对于任何想要将多维数组转换为单维数组的人来说:

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; 
}