php stdClass对象和数组如何使用php

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5156841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:58:38  来源:igfitidea点击:

stdClass Object and array how to using php

phparraysobjectstdclass

提问by user638009

I'm trying to get the twelve ids that this structure shows:

我正在尝试获取此结构显示的十二个 ID:

stdClass Object
(
    [checkins] => stdClass Object
        (
            [count] => 12
            [items] => Array
                (
                    [0] => stdClass Object
                        (

                            [venue] => stdClass Object
                                (
                                    [id] => 4564654646456
                                    .
                                    .

I do:

我愿意:

$checkins = $fsObjUnAuth->get("/users/self/checkins");
$count = $checkins ->response->checkins->count;  // so I can  get 12

 for( $i = 0; $i < $count; $i ++)
  {
      $a1[] = $checkins['items'][$i]['venue']['id'];  //two tries
      $a2[] = $checkins ->response->checkins->items->$i->venue->id;
        echo $i; echo ": ";
        echo $a1;echo"<br>";
        echo $a2;echo"<br>"
  } 

But I get: Fatal error: Cannot use object of type stdClass as array in line..

但我得到:致命错误:无法将 stdClass 类型的对象用作数组中的行..

Please can someone show me how to do this?

请有人告诉我如何做到这一点?

Thanks a lot

非常感谢

回答by meagar

You cannot access object members via the array subscript operator [].

您不能通过数组下标运算符访问对象成员[]

You have to use the ->operator:

您必须使用->运算符:

$x = new StdClass();

$x->member = 123;

In your case you'll have to use a mixture, since you have an object ($checkins) with a member ($items) which is an array, which contains additional objects.

在您的情况下,您必须使用混合,因为您有一个对象 ( $checkins) 和一个成员 ( $items),它是一个数组,其中包含其他对象。

$a1[] = $checkins->items[$i]->venue->id;

回答by Breith

Here is a simple solution to converta stdClass Objectin array in php with function get_object_vars

这是一个简单的解决方案,用于在 php 中使用函数转换数组中的stdClass 对象get_object_vars

Look at : http://php.net/manual/fr/function.get-object-vars.php

看看:http: //php.net/manual/fr/function.get-object-vars.php

Ex :

前任 :

debug($array);
$var = get_object_vars($array);
debug($var);

Or replace debugby print_r

或者替换debugprint_r

I'm use CakePHP framework

我正在使用 CakePHP 框架

Cdt

回答by diEcho

change

改变

$a1[] = $checkins['items'][$i]['venue']['id'];

changed to

变成

$a1[] = $checkins->items[$i]->venue->id;