【问题标题】:Accessing a PHP array object(stdClass) values访问 PHP 数组对象(stdClass)值
【发布时间】: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]-&gt;name;
  • 为什么这必须有效^)?
  • 我这样做了,并且使用了 terms[157] 有效,但是这不会改变吗?我只想要数组中的第一个位置。条款[0]->名称不起作用。

标签: php arrays wordpress object


【解决方案1】:

函数get_the_terms返回一个数组,该数组由每个元素的term_id索引。

这就是为什么$terms[157]$terms[151] 可以正常工作的原因。有关此行为的详细信息,请参阅PHP reference on arrays

您最好的选择是坚持使用内置的foreach,它的工作原理与您的问题中所述相同。

【讨论】:

  • 感谢@dehrg,但请参阅我上面的评论。这是我在 for 循环中尝试的第一件事。
  • 是的,for 循环的目的是限制显示的类别数量。在这种情况下只有 2 个。
  • 你为什么不想使用foreach?鉴于该函数返回一个具有奇数索引的数组,这似乎是您最好的选择。
  • 好的,只是构建递增的 var 来限制循环?但我更关心为什么 terms[0] 或 terms[1] 不起作用。
  • 编辑回答您的问题
【解决方案2】:

在 for 循环中,您尝试直接访问数组中的名称,而不是 stdclass 对象。

您需要使用$i 变量作为数组的索引。

for ($i=1; $i<3; $i++) {
    $term = $terms[$i]->name;
    echo $term;
}

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2016-07-09
      • 2016-11-12
      • 1970-01-01
      • 2010-11-22
      • 2012-05-28
      • 2014-02-28
      • 1970-01-01
      • 1970-01-01
      • 2013-01-25
      相关资源
      最近更新 更多