【问题标题】:PHP & Wordpress: print array contentPHP & Wordpress:打印数组内容
【发布时间】:2012-07-17 06:59:16
【问题描述】:

我现在很笨……

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 蛞蝓? 我认为 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;
    }
}

【问题讨论】:

    标签: php arrays wordpress


    【解决方案1】:

    试试

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

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

    【讨论】:

      【解决方案2】:

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

      echo $terms[7]->slug;
      

      有多个“东西”

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

      【讨论】:

      • 谢谢,我更新了我的问题。问题是这个“7”是专门针对wordpress中每个帖子的动态数字。我不知道它是什么号码。好像不是post->ID
      • @matt Array $terms 总是有一个元素,还是可以有更多?
      • 我猜它可能有更多。通常它设置为一个,但可以在帖子中添加多个术语。
      【解决方案3】:

      试试这个。

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

      【讨论】:

        【解决方案4】:

        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】:

          或者,让事情复杂一点:

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

          【讨论】:

            【解决方案6】:

            函数使用 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

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2017-01-24
              • 1970-01-01
              相关资源
              最近更新 更多