PHP& Wordpress:打印数组内容

时间:2012-07-18 09:15:23

标签: php arrays wordpress

我现在要愚蠢......

print_r($terms);

这样做......

Array
(
    [7] => stdClass Object
        (
            [term_id] => 7
            [name] => Testwhatever
            [slug] => testwhatever
            [term_group] => 0
            [term_taxonomy_id] => 7
            [taxonomy] => event_type
            [description] => 
            [parent] => 0
            [count] => 2
            [object_id] => 8
        )

)

我怎样才能print slu g? 我认为print print($terms->slug)应该完成这项工作,但它说:“试图获得非对象的属性”

更新

function get_event_term($post) {
    $terms = get_the_terms( (int) $post->ID, 'event_type' );
    if ( !empty( $terms ) ) {
        print_r($terms);
        return $terms[7]->slug;
    }
}

6 个答案:

答案 0 :(得分:3)

它是一个对象数组(即使它只包含索引为“7”的单个条目),而不是单个对象

echo $terms[7]->slug;

有多个“事物

foreach ($terms as $term) echo $term->slug;

答案 1 :(得分:2)

尝试

print_r($terms[7]->slug);

你的对象stdclass在数组[7]偏移量中。

答案 2 :(得分:2)

或者,稍微复杂一点:

array_walk($terms, function($val,$key) use(&$terms){ 
    var_dump($val->slug);
});

答案 3 :(得分:0)

试试这个。

print ($terms[7]->slug);

答案 4 :(得分:0)

print_r ($terms[7]->slug)看起来很合乎逻辑,因为它是一个对象数组

<强>更新

由于您不确定应返回多少项get_event_term,因此应返回一个数组。

function get_event_term($post) {
    $aReturn = array();
    $terms = get_the_terms( (int) $post->ID, 'event_type' );
    if ( !empty( $terms ) ) {
        print_r($terms);
        foreach($terms as $term){ // iterate through array of objects
            $aReturn[] = $term->slug; // get the property that you need
        }
    }
    return $aReturn;
}

答案 5 :(得分:0)

使用 wp_parse_args 系统管理其单个 $ args 参数的功能,可以为您提供所需的任何值。在这种情况下,$ args存储详细的显示覆盖,这是在许多WordPress函数中找到的模式。

$args = wp_parse_args( $args, $term->name );
echo $arg[157]['term_id']; //output 157
echo $arg[157]['name'];  //output Entertainment

为我提供更多详细信息

http://codex.wordpress.org/Function_Reference/wp_parse_args