我有一个关于用另一种方式来理解这段代码的问题,因为它没有做我想让它做的事情。
我正在创建一个论坛列表,该列表将显示该类别下的部分。好吧,这就是问题所在,因为您可以看到我有一个 If () {}Else {} 语句,用于将我想要的信息放入该列表中。问题是我需要在该类别下的最后一部分添加一个特殊的类,该类将称为 last-tr。现在我遇到的问题是所有信息都出现在屏幕上,但该类仅适用于最后一行,现在是所有类别的最后一行,这就是我正在寻找的。
所以像这样的事情,
Welcome Center
Introduce Yourself
Say Hello To our Admins (last-tr)
Game
COD
BF4 (last-tr)
Code
PHP
Java
PDO (last-tr)
但我的代码给我的是
Welcome Center
Introduce Yourself
Say Hello To our Admins
Game
COD
BF4
Code
PHP
Java
PDO (last-tr) <- Just that one.
这是代码
<?php
include '../../core/init.php';
include '../../includes/head.php';
//Getting Categories under Welcome
$db = DB::getInstance();
$user = New User();
$forum = New Forum();
$list = '';
$category = $db->query('SELECT * FROM forum_categories');
foreach ($category->results() as $category) {
$list .= '<thead>';
$list .= '<tr>';
$list .= '<th class="titles">' . $category->title . '</th>';
$list .= '<th>Last Post</th>';
$list .= '<th>Topics</th>';
$list .= '<th>Replies</th>';
$list .= '</tr>';
$list .= '</thead>';
$list .= '<tbody>';
$sections = $db->query("SELECT * FROM forum_section WHERE category_id = '$category->id'");
foreach ($sections->results() as $section) {
$x = 0;
if ($x < $sections->count()) {
$list .= '<tr>';
$list .= '<td>';
$list .= '<a href="/category.php?id='. $section->id .'">';
$list .= '<img scr="/images/icons/iconmonstr/intro.png">';
$list .= '</a>';
$list .= '<a href="/category.php?id='. $section->id .'">' . $section->title . '</a>';
$list .= '<span>' . $section->desc . '</span>';
$list .= '</td>';
$list .= '<td> Nasty </td>';
$list .= '<td> 0 </td>';
$list .= '<td> 0 </td>';
$list .= '</tr>';
$x++;
}else {
$list .= '<tr class="last-tr">';
$list .= '<td>';
$list .= '<a href="/category.php?id='. $section->id .'">' . $section->title . '</a>';
$list .= '</td>';
$list .= '<td> Nasty </td>';
$list .= '<td> 0 </td>';
$list .= '<td> 0 </td>';
$list .= '</tr>';
}
}
$list .= '</tbody>';
}
?>
<link rel="stylesheet" href="/css/fourms.css">
<title>Forums</title>
</head>
<body>
<?php include '../../includes/header.php'; ?>
<section id="main_section">
<section id="main_content">
<div id="forum-section">
<table class="forumlist">
<?php echo $list; ?>
</table>
</div>
</section>
</section>
<?php include('../../includes/footer.php'); ?>
你的 if 语句应该是if ($x < $sections->count()-1)
的,因为数组的最后一个索引总是 count-1,因为从 0 开始。
或
您也可以通过从 1 开始$x
来修复它,因为您使用的是侧面计数器的foreach
,因此您不会得到索引外错误。 换句话说:
foreach ($sections->results() as $section) {
$x = 1;
if ($x < $sections->count()) {
...
$x++;
}else {
...
}
}
但是选择第一种选择可能更直接。
您正在针对整个类进行测试,而不是针对类中的数据进行测试.
$sections->count() 计算所有部分,而不是您正在处理的一个部分中的条目.
您需要测试单数部分的计数
所以如果你有
$sectionsAll = 数组(
sectionOne = array( 1, 2, 3),
sectionTwo = array( 1, 2, 3),
部分三 = 数组( 1, 2, 3)
);
您目前正在$sectionsAll上进行测试,您需要检查第一节、第二节、第三节