Roooss
Roooss

Reputation: 634

iterating through php object elements

this problem is confusing me as i am sure the syntax is correct (although clearly not :-/)

I have an object that looks like this...

[result]  stdClass Object
(
    [aResult] => stdClass Object
        (
            [status] => 0
            [Message] => Success
            [container] => stdClass Object
                (
                    [a] => a
                    [b] => b
                    [c] => c
                    [d] => d
                    [e] => e
                    [f] => f
                    [g] => g
                    [h] => h
                    [i] => i
                    [j] => j
                )

        )

)

No i am trying to pull out the values in the 'container' array. To do this i have the following code...

//pull out array result
    $myDetails = $result->aResult->container;
    foreach( $myDetails as $key)
    {
        echo "<p>";
        echo "<b>a</b>: ".$key->a."<br />";
        echo "<b>b</b>: ".$key->b."<br />";
        echo "<b>c</b>: ".$key->c."<br />";
        echo "<b>d</b>: ".$key->d."<br />";
        echo "<b>e</b>: ".$key->e."<br />";
        echo "<b>f</b>: ".$key->f."<br />";
        echo "<b>g</b>: ".$key->g."<br />";
        echo "<b>h</b>: ".$key->h."<br />";
        echo "<b>i</b>: ".$key->i."<br />";
        echo "<b>j</b>: ".$key->j."<br />";
        echo"</p>";
    }

But all i get is the following error for each of the '$key->X' calls...

Notice: Trying to get property of non-object in

Im honestly unsure what I am doing wrong..... any help is as always greatly appreciated.

Upvotes: 1

Views: 120

Answers (3)

user680786
user680786

Reputation:

Variable myDetails contains object, in foreach you are iterating properties of that object, properties is not objects but arrays, so why you see this error message.

Upvotes: 0

Roooss
Roooss

Reputation: 634

Thanks to some joggery form a friend the fix is the following...

//pull out array result
    $myDetails = $result->aResult->container;

    echo "<p>";
    foreach( $myDetails as $key=>$value)
    {

        echo "<b>".$key."</b>: ".$value."<br />";

    }

    echo"</p>";

Upvotes: 1

Karoly Horvath
Karoly Horvath

Reputation: 96258

either remove the foreach, or:

foreach( $myDetails as $k=>$v) {
    echo "<b>$k</b>: $v<br />";
}

Upvotes: 1

Related Questions