How to get the value of mixed of array and objects

79 views Asked by At

How to get the value of Bar Foo?

Array
(
    [channel] => SimpleXMLElement Object
        (
            [item] => Array
                (
                    [0] => SimpleXMLElement Object
                        (
                            [title] => Bar Foo
                        )
                )
        )
)
echo $sxml['channel']->item[$i]->title;

It gives result, but with Notice: Trying to get property of non-object

1

There are 1 answers

0
Jonathan Tweedy On

If your object is structured like this: (object > array > object > array), then you're calling the indexes/keys wrong. Note the example below:

$x = new stdClass();
$x->channel = array();
$y = new stdClass();
$y->title = "Bar Foo";
$x->channel[0] = $y;
//echo $x['channel']->item[$i]->title;
//// Fatal error: Cannot use object of type stdClass as array
echo $x->channel[0]->title;
//// Success

But if it's structured the way you describe, then your echo line gives me correct output (see below), so you're probably creating an array or object somewhere that doesn't properly map to what you described in the pseudo-code above.

$x = array();
$x['channel'] = new stdClass();
$x['channel']->item = array();
$x['channel']->item[0] = new stdClass();
$x['channel']->item[0]->title = "Bar Foo";
echo $x['channel']->item[0]->title;

On a side note, if you find that you need to "dollar sign" complicated structures (like dynamic variable names involving array indexes), you can do so using braces like this:

$x = 2;
$y = array("x"=>$x);
print $($y['x']);