使用Wordpress不能使用stdClass类型的对象作为数组

时间:2022-10-23 07:59:36

I am trying to retrieve the slug for a tag inside a wordpress post, now its possible to get all tag info using

我正在试图找回一个wordpress贴子里的标签,现在可以使用所有的标签信息

$tag = wp_get_post_tags($post->ID);

More info on this on the Wordpress Docs

更多关于这方面的信息在Wordpress文档

By using this you should get data returned like this...

通过使用这个,你应该得到像这样返回的数据……

Array
(
   [0] => stdClass Object
       (
           [term_id] => 4
           [name] => tag2
           [slug] => tag2
           [term_group] => 0
           [term_taxonomy_id] => 4
           [taxonomy] => post_tag
           [description] => 
           [parent] => 0
           [count] => 7
       )

   [1] => stdClass Object
       (
           [term_id] => 7
           [name] => tag5
           [slug] => tag5
           [term_group] => 0
           [term_taxonomy_id] => 7
           [taxonomy] => post_tag
           [description] => 
           [parent] => 0
           [count] => 6
       )

)

Now what I want is the slug for the first item which should be as follows

现在我想要的是第一个项目的段首,应该是这样的

$tag[0]['slug']

However by doing so I recieve this php error:

然而,通过这样做,我收到了这个php错误:

Cannot use object of type stdClass as array

不能使用类型为stdClass的对象作为数组

Can someone tell me what I'm doing wrong here? and whats the best way to get the slug data

有人能告诉我我做错了什么吗?什么是获得鼻涕虫数据的最好方法

2 个解决方案

#1


55  

Note that the array contains objects (instances of stdClass), not other arrays. So the syntax is:

注意,数组包含对象(stdClass实例),而不是其他数组。所以语法是:

$tag[0]->slug

#2


3  

Another option should be to explicitly cast $tag[0] into an array:

另一个选项应该是显式地将$tag[0]转换为一个数组:

$t = (array)$tag[0];
$t["slug"] = ...

Can't get it to work though

但是它不能工作吗

#1


55  

Note that the array contains objects (instances of stdClass), not other arrays. So the syntax is:

注意,数组包含对象(stdClass实例),而不是其他数组。所以语法是:

$tag[0]->slug

#2


3  

Another option should be to explicitly cast $tag[0] into an array:

另一个选项应该是显式地将$tag[0]转换为一个数组:

$t = (array)$tag[0];
$t["slug"] = ...

Can't get it to work though

但是它不能工作吗