如何从mysql select中为每条记录呈现不同的标记?

时间:2015-07-23 01:19:22

标签: php html mysql

我有一组可以从mysql中选择的项目。然后我想在我的页面上用不同的标记显示这些项目。

这就是我的HTML每个项目的样子。

<ul class='unstyled main-facilities row'>
    <li class='info-facility-item '>
        <span class='fa-stack'>
            <i class='fa fa-square fa-stack-2x'></i>
            <i class='fa fa fa-cutlery fa-stack-1x fa-inverse'></i>
        </span> Item-01
    </li>
    <li class='info-facility-item '>
        <span class='fa-stack'>
            <i class='fa fa-square fa-stack-2x'></i>
            <i class='fa fa fa-rss fa-stack-1x fa-inverse'></i>
        </span> Item-02
    </li>
    <li class='info-facility-item '>
        <span class='fa-stack'>
            <i class='fa fa-square fa-stack-2x'></i>
            <i class='fa fa-refresh fa-stack-1x fa-inverse'></i>
        </span> Item-03
    </li>
    ...
    ...
    ...

</ul>

如果我对每个项目都有相同的标记,那么我可以这样做:

// Fetch all the records:
while ($stmt->fetch()) {

    $result  = "<li class='info-facility-item '>\n";
    $result .= "    <span class='fa-stack'>\n";
    $result .= "        <i class='fa fa-square fa-stack-2x'></i>\n";
    $result .= "        <i class='fa fa fa-rss fa-stack-1x fa-inverse'></i>\n";
    $result .= "    </span>{$item}\n";
    $result .= "</li>\n";
    $items[] = $result;     
    }           
}   

但我不知道如何修改我的while循环以为每个项目呈现不同的标记。

任何人都可以告诉我有没有办法在PHP中执行此操作?

谢谢。

2 个答案:

答案 0 :(得分:1)

下面的

代码生成4个不同的css类,这些类被添加到顺序LI中。如果您愿意 - 您可以在其他地方添加更多类似的类。新课程的名称为new_class0new_class1,... 这就是你需要的吗?

<?php
//Fetch all the records:
$xi = 0;
while ($stmt->fetch()) {
    if ( $xi > 3 ) {
        $xi = 0;
    }
    $result  = "<li class=\"info-facility-item new_class{$xi}\">\n";
    $result .= "    <span class='fa-stack'>\n";
    $result .= "        <i class='fa fa-square fa-stack-2x'></i>\n";
    if ( $xi == 0 ) {
        $result .= "        <i class='fa fa fa-rss fa-stack-1x fa-inverse'></i>\n";
    else if ( $xi == 1 ) {
        $result .= "        <i class='fa fa fa-cutlery fa-stack-1x fa-inverse'></i>\n";
    }
    $result .= "    </span>{$item}\n";
    $result .= "</li>\n";
    $items[] = $result;      
    $xi += 1;                    
}

答案 1 :(得分:0)

如果你知道需要设置到每个位置的值,你可以这样解决: 查看数组$val

$val= array("value0", "value1", "value2");
$i = 0;
// Fetch all the records:
while ($stmt->fetch()) {

    $result  = "<li class='info-facility-item '>\n";
    $result .= "    <span class='fa-stack'>\n";
    $result .= "        <i class='fa fa-square fa-stack-2x'></i>\n";
    $result .= "        <i class='fa fa {$val[$i]} fa-stack-1x fa-inverse'></i>\n";
    $result .= "    </span>{$item}\n";
    $result .= "</li>\n";
    $items[] = $result;     
    $i++;           
}