全部, 我有以下代码从Wordpress中选择一些类别:
$args = array(
'type' => 'post',
'hide_empty' => 0
);
$categories = get_categories( $args );
当我打印出数组时,我得到以下输出:
Array ( [0] => stdClass Object ( [term_id] => 4 [name] => Baseball [slug] => baseball [term_group] => 0 [term_taxonomy_id] => 4 [taxonomy] => category [description] => [parent] => 0 [count] => 29 [cat_ID] => 4 [category_count] => 29 [category_description] => [cat_name] => Baseball [category_nicename] => baseball [category_parent] => 0 ) [1] => stdClass Object ( [term_id] => 2 [name] => Football [slug] => football [term_group] => 0 [term_taxonomy_id] => 2 [taxonomy] => category [description] => [parent] => 0 [count] => 4 [cat_ID] => 2 [category_count] => 4 [category_description] => [cat_name] => Football [category_nicename] => football [category_parent] => 0 ) [2] => stdClass Object ( [term_id] => 1 [name] => Uncategorized [slug] => uncategorized [term_group] => 0 [term_taxonomy_id] => 1 [taxonomy] => category [description] => [parent] => 0 [count] => 21 [cat_ID] => 1 [category_count] => 21 [category_description] => [cat_name] => Uncategorized [category_nicename] => uncategorized [category_parent] => 0 ) )
这是我的foreach循环,用于显示数组的内容:
foreach($categories as $category){
if ($category->name != 'Uncategorized') {
echo '<option value="'.$category->term_id.'"> '.$category->name.'<option>';
}
}
由于某种原因,foreach循环在具有值的选项之间添加了一个空白选项。这会是什么?
答案 0 :(得分:0)
您需要将<option>
替换为</option>
:
foreach($categories as $category){
if ($category->name != 'Uncategorized') {
echo '<option value="'.$category->term_id.'"> '.$category->name.'</option>';
}
}
HTML标记始终采用以下形式:
<foo>...</foo>
有一些不要求儿童元素或文字的例外情况:
<input>
或
<input/>