【发布时间】:2014-10-17 10:16:58
【问题描述】:
我正在使用 WordPress 的原生函数 get_the_terms 它返回这个数组,里面有一个对象:
array (size=2)
157 =>
object(stdClass)[41]
public 'term_id' => int 157
public 'name' => string 'Entertainment' (length=13)
public 'slug' => string 'entertainment' (length=13)
public 'term_group' => int 0
public 'term_taxonomy_id' => int 157
public 'taxonomy' => string 'category' (length=8)
public 'description' => string '' (length=0)
public 'parent' => int 0
public 'count' => int 1
public 'object_id' => int 644
public 'filter' => string 'raw' (length=3)
151 =>
object(stdClass)[40]
public 'term_id' => int 151
public 'name' => string 'Featured' (length=8)
public 'slug' => string 'featured' (length=8)
public 'term_group' => int 0
public 'term_taxonomy_id' => int 151
public 'taxonomy' => string 'category' (length=8)
public 'description' => string '' (length=0)
public 'parent' => int 0
public 'count' => int 1
public 'object_id' => int 644
public 'filter' => string 'raw' (length=3)
如何访问
public 'name' => string 'Featured' (length=8)
这行得通
$terms = get_the_terms( $post->ID, 'category' );
foreach ($terms as $term) {
$test = $term->name;
echo $test;
}
这不起作用:
for($i=1; $i<3; $i++) {
$term = $terms->name;
echo $term;
}
这也行不通
for($i=1; $i<3; $i++) {
$term = $terms[0]->name;
//$term = $terms[1]->name;
//$term = $terms[157]->name; // works but not reliable
echo $term;
}
为什么?
【问题讨论】:
-
因为您没有使用索引来访问您想要的 aray 成员。试试
$term = $terms[$i]->name; -
为什么这必须有效^)?
-
我这样做了,并且使用了 terms[157] 有效,但是这不会改变吗?我只想要数组中的第一个位置。条款[0]->名称不起作用。
标签: php arrays wordpress object