【问题标题】:Issue with if statement in PHP codePHP代码中if语句的问题
【发布时间】:2016-10-15 09:14:21
【问题描述】:

我第一次有这个代码:

foreach( $results as $row ) {
    if ($row['class'] <>$class) {
        echo "<tr><td><p class=\"boldtitle\">".$row['class']."</p></td></tr>";
    }
    echo "
    <tr>
        <td><a href=\"".$row['hyperlink']."\">".$row['title']."</a></td>
    </tr>
    ";
    $class = $row['class'];
}
}

这很好,但我希望当".$row['hyperlink']." 等于"NULL" 时 HTML 超链接标签消失。

为此,我写了这样的代码:

$class = $row['class'];
foreach( $results as $row ) {
    if ($row['class'] <>$class) {
        echo "<tr><td><p class=\"boldtitle\">".$row['class']."</p></td></tr>";
    }
    if ($row['hyperlink'] != "NULL")    {
        echo "<tr><td><a href=\"".$row['hyperlink']."\">".$row['title']."</a></td></tr>";
    } else {
        echo "<tr><td>".$row['title']."</td></tr>";
    }
}
}
?>

根据需要设置或删除超链接,但分组功能也丢失了。

代替:

**Cleaner**
David
Phil
Gustav
**Farmer**
Lynn
Peter
**Mason**
Brion
Alf

我明白了:

**Cleaner**
David
**Cleaner**
Phil
**Cleaner**
Gustav
**Farmer**
Lynn
**Farmer**
Peter
**Mason**
Brion
**Mason**
Alf

有人知道我做错了什么吗?我的错在哪里?

【问题讨论】:

  • 我猜你想要的是$row['hyperlink'] != "NULL"而不是$row['hyperlink'] != null(没有引号)
  • @jszobody 也许。这个问题非常模糊。我们需要知道数据是如何构造的。
  • 你的 foreach 中有 4 个 { 和 5 } ..

标签: php html mysql sql hyperlink


【解决方案1】:

在您的第二段代码中,您将 $class = $row['class']; 移到了 foreach 循环之外。这意味着它最初将设置为 null(因为 $row['class'] 在循环之前未定义),因此 $row['class'] &lt;&gt;$class 将始终为 true。将它移回循环内,它应该像以前一样工作。

$class = null; // initialize $class to null
foreach( $results as $row ) {
    if ($row['class'] <>$class) {
        echo "<tr><td><p class=\"boldtitle\">".$row['class']."</p></td></tr>";
    }
    if ($row['hyperlink'] != "NULL") {
        echo "<tr><td><a href=\"".$row['hyperlink']."\">".$row['title']."</a></td></tr>";
    } else {
        echo "<tr><td>".$row['title']."</td></tr>";
    }
    $class = $row['class']; // reset $class to the current value here
}

【讨论】:

  • 做到了。非常感谢。
猜你喜欢
  • 2011-05-11
  • 1970-01-01
  • 2016-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多