我有以下代码从我的数据库中获取字段并将它们放入 html 表单的格式下拉菜单中。以目前的形式,我从我的数据库中获取了 3 次,代码的工作原理在代码的注释中进行了解释:
$getSolos = $wpdb->get_results($wpdb->prepare("
SELECT * FROM wp_terms p
LEFT OUTER JOIN wp_term_taxonomy t ON p.term_id = t.term_id
WHERE t.taxonomy = 'format'
AND t.parent = 0
AND t.term_id NOT IN (SELECT parent FROM wp_term_taxonomy WHERE taxonomy = 'format' AND parent > 0)
ORDER BY t.parent
")); // This fetches all rows that do not have children or parents.
$getParents = $wpdb->get_results($wpdb->prepare("
SELECT * FROM wp_terms p
LEFT OUTER JOIN wp_term_taxonomy t ON p.term_id = t.term_id
WHERE t.taxonomy = 'format'
AND t.parent = 0
AND t.term_id IN (SELECT parent FROM wp_term_taxonomy WHERE taxonomy = 'format' AND parent > 0)
")); // This fetches all rows that have children
$getChildren = $wpdb->get_results($wpdb->prepare("
SELECT * FROM wp_terms p
LEFT OUTER JOIN wp_term_taxonomy t ON p.term_id = t.term_id
WHERE t.taxonomy = 'format'
AND t.parent > 0
ORDER BY t.parent
AND p.name
")); //This fetches all rows that ARE children
<select name="format"> //start the dropdown
<option value="empty"></option> //default field is empty
<?php
foreach ($getSolos as $solo) { //start loop through solos for output
echo "<option value='".$solo->name."'>".$solo->name."</option>"; // output solos as options in the dropdown
}
foreach ($getParents as $parent) { //start loop through parents for output
echo "<optgroup label='".$parent->name."'>"; // Spit out parent as an optgroup
foreach ($getChildren as $child) { //Start loop through children for output
if ($child->parent == $parent->term_id) { // if child's parent value matches the ID of the parent
echo "<option value='".$child->name."'> ".$child->name."</option>"; //Spit out the child as an option
}
}
echo "</optgroup>"; //close the optgroup
}
?>
</select> // end the dropdown
输出如下:
Entry Form
Twitter
Facebook
- Entry Form
- Page
数据库中的组合表如下所示:
term_id name slug taxonomy parent
1 Entry Form entry-form format 0
2 Page page format 3
3 Facebook facebook format 0
4 Entry Form facebook-entry-form format 3
5 Twitter twitter format 0
然而,这种方法存在一个问题。
1)3次访问数据库效率低下。
2)如果一个孩子也有一个孩子是无效的。虽然 children 的孩子都进入 $getChildren,但代码只会吐出 1 级孩子并忽略其余部分。
出于演示目的,如果我有第 6 行:
term_id name slug taxonomy parent
6 Single single format 2
然后代码会这样做:
Entry Form
Twitter
Facebook
- Entry Form
- Page
请注意, Single 被完全忽略,尽管它包含在 $getChildren 数组中。
那么如何才能使这段代码变得更好呢?