使用 PHP 在 assoc 数组中使用按钮名称筛选表

我想要实现的目标


我目前得到了一个巨大的集合,其中包含超过一千行和10 +列,解析为带有PDO的表。之后有必要过滤表格,我决定使用PHP来执行此操作。


我目前的方法工作正常,但我不确定它是否在性能方面效率较低,因为有很多语句使代码看起来很混乱。else if


我目前的方法


我得到了一个“过滤表”HTML按钮,它打开了一个弹出窗口,其中包含表单中的几个按钮(15个以上)。每个按钮名称都有自己的筛选器查询。


然后,我检查单击了哪个按钮,然后将筛选器查询附加到我的实际SQL中,以解析整个表。


我的代码


菲律宾比索:


if (isset($_POST['filter_type_pc'])) {

    $newFilter = "WHERE type LIKE 'PC%' ORDER BY time_altered DESC";

} else if (isset($_POST['filter_type_mac'])) {

    $newFilter = "WHERE type LIKE 'Mac%' ORDER BY time_altered DESC";

} else if (isset($_POST['filter_type_linux'])) {

    $newFilter = "WHERE type LIKE 'Linux%' ORDER BY ip DESC";


    //...

    //there are more 'else if' statements, but I've excluded them to maintain a clean question

    //...


} else {

    $newFilter = "ORDER BY time_altered DESC";

}


$sql = "SELECT * FROM myTable $newFilter";

$stmt = $conn->prepare($sql);

$stmt->execute();

$result = $stmt->fetchAll();

值得注意的是(?),过滤器查询可能完全不同。我不仅使用“位置”或“LIKE”子句。


网页:


<form id="filterTable" name="filter" method="POST" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">

    <h5>Type of device</h5>

    <button type="submit" class="btn btn-light filter_button" name="filter_type_pc">PC</button>

    <button type="submit" class="btn btn-light filter_button" name="filter_type_mac">Mac</button>

    <button type="submit" class="btn btn-light filter_button" name="filter_type_linux">Linux</button>

</form>

我的问题


为了进一步澄清,我将问一个问题。如果有的话,什么会是更好,更清洁的方法,而不是这种混乱?我有兴趣听听你的建议,因为我想从中学习并从已经工作的代码中改进!else if


炎炎设计
浏览 97回答 1
1回答

GCT1015

回答我自己的问题,以便任何像您这样偶然发现这篇文章的未来访问者都可以学习到这个问题的简单化解决方案。$filters = array(&nbsp; &nbsp; "filter_type_pc" => "My SQL query",&nbsp; &nbsp; "filter_type_mac" => "My SQL query",&nbsp; &nbsp; "filter_type_linux" => "My SQL query");if (!empty($_POST)) {&nbsp; &nbsp; $arrayMatch = array_intersect_key($_POST, $filters);&nbsp; &nbsp; foreach(array_keys($arrayMatch) as $filterName) {&nbsp; &nbsp; &nbsp; &nbsp; $newFilter = $filters[$filterName];&nbsp; &nbsp; }} else {&nbsp; &nbsp; $newFilter = "ORDER BY time_altered DESC";};让我们来分解一下:首先,我们检查请求是否为空,因为我们无法知道使用PHP在DOM中单击了哪个过滤器按钮,因此我们将其留空。$_POST因为我们检查了整个超级全局变量,所以它会在请求中采取任何东西,如果你有几个请求,我们通过以下方式解决这个问题:$_POST使用匹配键和数组。array_intersect_key$_POST$filters创建一个仅包含匹配结果的新数组。$arrayMatch然后,我们用 和 遍历新创建的数组的匹配键,然后将键命名为 。foreach()array_keys()$filterName最后,我们可以通过使用新变量将数组的值定义为数组的值来获得数组的值。$newFilter$filters$filterName编辑:我想出了一个比上面更好的解决方案,而上面的解决方案按预期工作 - 它可能会与前面提到的未来实现发生冲突。这将解决此问题,并且仅检查包含数组中键的请求。POST$filters = array(&nbsp; &nbsp; "filter_type_pc" => "My SQL query",&nbsp; &nbsp; "filter_type_mac" => "My SQL query",&nbsp; &nbsp; "filter_type_linux" => "My SQL query");$newFilter = "ORDER BY time_altered DESC";$arrayMatch = array_intersect_key($_POST, $filters);foreach(array_keys($arrayMatch) as $filterName) {&nbsp; &nbsp; if (isset($_POST[$filterName])) {&nbsp; &nbsp; &nbsp; &nbsp; $newFilter = $filters[$filterName];&nbsp; &nbsp; }};
打开App,查看更多内容
随时随地看视频慕课网APP