我有一个表,使用 foreach() 显示数组中的每个对象。我想要一个搜索栏,可以过滤表格,仅显示一个对象及其信息。我已经使用这个系统为每个键实现了这一点:
$searchname = $_SESSION["searchname"];
if($contents["attributes"]["Description"] == $searchname) {
$description = $contents["attributes"]["Description"];
}
else {
$description = '';
}
但是,这会使每隔一行为空,但由于 else {''} 的原因,仍然被打印为一行。
我尝试使用来自这个问题的一些JavaScript查询隐藏每个“空”行,
deleteEmptyRows();
function checkIfCellsAreEmpty(row) {
var cells = row.cells;
var isCellEmpty = false;
for(var j = 0; j < cells.length; j++) {
if(cells[j].innerHTML !== '') {
return isCellEmpty;
}
}
return !isCellEmpty;
}
function deleteEmptyRows() {
var myTable = document.getElementById("myTable");
for(var i = 0; i < myTable.rows.length; i++) {
var isRowEmpty = checkIfCellsAreEmpty(myTable.rows[i]);
if (isRowEmpty) {
myTable.rows[i].style.display = "none";
}
}
}
但这似乎也不起作用,每一行仍然显示。
if(isset($_POST['submit_search']) && !empty($_POST['submit_search'])) {
$_SESSION["searchname"] = $_POST['submit_search'];
}
$json = json_decode($buffer, true);
$info = $json["features"];
?><div><table id="myTable"><tr><th>Beach Name</th><th>Patrolled by</th><th>Patrol freq</th><th>Updated</th></div><?php
foreach ($info as $contents){
$searchname = $_SESSION["searchname"];
if($contents["attributes"]["Description"] == $searchname) {
$description = $contents["attributes"]["Description"];
}
else {
$description = '';
}
if($contents["attributes"]["Description"] == $searchname) {
$patrolledby = $contents["attributes"]["PatrolledBy"];
}
else {
$patrolledby = '';
}
if($contents["attributes"]["Description"] == $searchname) {
$mil = $contents["attributes"]["last_edited_date"];
$seconds = $mil / 1000;
$date = date("d/m/Y", $seconds);
}
else {
$date = '';
}
if($contents["attributes"]["Description"] == $searchname) {
$patrolfreq = $contents["attributes"]["PatrolFrequency"];
}
else {
$patrolfreq = '';
}
print("<table>");
printf("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>", $description, $patrolledby, $patrolfreq, $date);
print("</table>");
}
}
现在,在搜索“Mooloolaba Beach”海滩之后,我留下了类似的东西:
海滩名称 | 巡逻者 |
---|---|
穆卢拉巴海滩 | 理事会 |
穆卢拉巴海滩 | 昆士兰州冲浪救生中心 |
我还在 if() 查询中尝试了 isset() 和 !empty(),但 isset() 似乎不适用于 '==' 运算符。
有没有办法隐藏这些空行或者只是阻止它们打印?
我建议您只使用一个 IF 条件,因为在每种情况下它都是相同的,然后将所有变量赋值放入其中。然后,您还在此
printf
条件中插入 IF
,并在循环外部的表中插入 print
。
print("<table>");
foreach ($info as $contents){
$searchname = $_SESSION["searchname"];
if($contents["attributes"]["Description"] == $searchname) {
$description = $contents["attributes"]["Description"];
$patrolledby = $contents["attributes"]["PatrolledBy"];
$mil = $contents["attributes"]["last_edited_date"];
$seconds = $mil / 1000;
$date = date("d/m/Y", $seconds);
$patrolfreq = $contents["attributes"]["PatrolFrequency"];
printf("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>", $description, $patrolledby, $patrolfreq, $date);
}
}
print("</table>");