简体   繁体   English

数组中的嵌入对象

[英]Embedded objects inside an array

I have an array named $result, the output for print_r($result) look like this. 我有一个名为$ result的数组, print_r($ result)的输出如下所示。

Array
(

[0] => Profile Object
    (
        [id] => 3
        [name] => alvis
        [parentLink] => ProfileLink Object
            (
                [href] => web
                [type] => data
            )
    )

[1] => Profile Object
    (
        [id] => 3
        [name] => gorgia
        [parentLink] => ProfileLink Object
            (
                [href] => text
                [type] => values
            )
    )

[2] => Profile Object
    (
        [id] => 4 
        [name] => text
        [parentLink] => ProfileLink Object
            (
                [href] => text
                [type] => values
            )
    )

 )

I tried displaying just the name by using: 我尝试使用以下方式显示名称:

foreach ($results[name] as $key => $value) {
            echo $key . ": " . $value."<br>";
            }

but I got an error Cannot use object of type Profile as array. 但我得到一个错误不能使用类型为Profile的对象作为数组。

and when I tried 当我试着

foreach ($results->name as $key => $value) {
            echo $key . ": " . $value."<br>";
            }

I got another error : Invalid argument supplied for foreach() 我收到另一个错误:为foreach()提供的参数无效
is there's away to display the id and the name? 有没有显示ID和名称?

You can use foreach to iterate through each profile object in your array, and then reference the properties of each profile using -> . 您可以使用foreach迭代数组中的每个配置文件对象,然后使用->引用每个配置文件的属性。 The code below ignores the numeric index of the array and just uses the id and name from the profile object. 下面的代码忽略了数组的数字索引,只使用了配置文件对象中的idname

foreach ($result as $profile) {
    echo $profile->id .": ".$profile->name . " <br>";
}

If you want to include the numeric index of the array as well: 如果要包含数组的数字索引:

foreach ($result as $index=>$profile) {
    echo "(index ". $index .") ".$profile->id.": ".$profile->name." <br>";
}

You need to loop through your $result array using foreach, and then access the "name" attribute using "->" notation. 您需要使用foreach遍历$ result数组,然后使用“ - >”表示法访问“name”属性。

    foreach ($result as $profile) {
            print $profile->name;
     }

If you want to get all properties of the profile object, you will have to use get_object_vars(). 如果要获取配置文件对象的所有属性,则必须使用get_object_vars()。

     foreach ($result as $profile) {
           $vars = get_object_vars($profile);
           foreach ($vars as $key => $var) {
                 echo $key . ": " . $var."<br>";
                 // add suitable looping for the ProfileLink object too
           }
     }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM