如何在for循环中只重复一次重复行?

时间:2014-04-18 22:44:11

标签: php

我编码了这个:

<?php

    $onlinecheck = mysql_query("SELECT * FROM online  order by id DESC");
   for($j=1; $onlinecheck1 = mysql_fetch_object($onlinecheck); $j++)
{   
$page               = $onlinecheck1->page;




echo $page;
}

?>

我的桌子是这样的:

1  index.php
2  index.php
3  contact.php
4  gallery.php

将按以下方式打印:

   index.php
   index.php
   contact.php
   gallery.php

但我想这样打印:

   index.php
   contact.php
   gallery.php

请帮帮我

2 个答案:

答案 0 :(得分:2)

创建一个关联数组,其键是您已打印的名称。在打印名称之前,请检查它是否已存在于阵列中。

$pages_printed = array();
for($j=1; $onlinecheck1 = mysql_fetch_object($onlinecheck); $j++)
{   
    $page = $onlinecheck1->page;
    if (!isset($pages_printed[$page])) {
        $pages_printed[$page] = true;
        echo $page;
    }
}
//I have added missed > )

答案 1 :(得分:1)

<?php

    $onlinecheck = mysql_query("SELECT * FROM online  order by id DESC");
    if ($onlinecheck) {
        $used = array();
        for($j=1; $onlinecheck1 = mysql_fetch_object($onlinecheck); $j++) {   
            $page = $onlinecheck1->page;
            if (!isset($used[$page]) || $used[$page] !== true) {
                $used[$page] = true;
                echo $page;
            }
        }
    }

?>