【发布时间】:2013-11-30 08:46:35
【问题描述】:
我正在编写自定义 WordPress 脚本,该脚本应该显示元素中的所有自定义分类。其中一些元素有子元素,而另一些则没有。这是表单的代码:
<?php
$terms = get_terms("location", "hide_empty=0");
$count = count($terms);
if ( $count > 0 ){
foreach ( $terms as $term ) {
echo "<option value='" . $term->slug . "'>" . $term->name ."</option>";
}
}
echo "</select>";
问题是,它按字母顺序显示所有元素,包括父母和孩子。我希望孩子嵌套在父母之下,但我不知道如何。谁能提供一些帮助?
这里是 $terms 数组的 print_r:
Array
(
[0] => stdClass Object
(
[term_id] => 18
[name] => Andrijevica
[slug] => andrijevica
[term_group] => 0
[term_taxonomy_id] => 18
[taxonomy] => location
[description] =>
[parent] => 0
[count] => 0
)
[1] => stdClass Object
(
[term_id] => 19
[name] => Berane
[slug] => berane
[term_group] => 0
[term_taxonomy_id] => 19
[taxonomy] => location
[description] =>
[parent] => 0
[count] => 0
)
[2] => stdClass Object
(
[term_id] => 17
[name] => Bijelo Polje
[slug] => bijelo-polje
[term_group] => 0
[term_taxonomy_id] => 17
[taxonomy] => location
[description] =>
[parent] => 0
[count] => 0
)
.....
[29] => stdClass Object
(
[term_id] => 53
[name] => Pobrežje
[slug] => pobrezje
[term_group] => 0
[term_taxonomy_id] => 63
[taxonomy] => location
[description] =>
[parent] => 4
[count] => 0
)
[30] => stdClass Object
(
[term_id] => 4
[name] => Podgorica
[slug] => podgorica
[term_group] => 0
[term_taxonomy_id] => 4
[taxonomy] => location
[description] =>
[parent] => 0
[count] => 7
)
如您所见,父母的父母为 0。子级的父级值设置为父级的 term_id。例如 [30] 是 [29] 的父级。
【问题讨论】:
-
这不是一个多维数组。它是一个对象数组..
-
原谅我的无知,我编辑了帖子。
-
无需原谅 :-) 我之所以这么说是因为语法发生了变化……例如:
$term[0]->slug