Access a nested object array

2019-07-28 18:39发布

问题:

Hey guys I can't seem to get the syntax here right, I'm just trying to see if type exists, I've tried

if($obj->type)    /* do something */
if($obj[0]->type) /* do something */
if($obj->type[0]) /* do something */

On this

stdClass::__set_state(
array(
   '0' => 
  stdClass::__set_state(
  array(
     'report_number' => '555',
     'type' => 'citrus',
     'region' => 'Seattle',
     'customer_number' => '9757',
     'customer' => 'The Name',
     'location' => 'West Seattle, WA',
     'shipper' => 'Yamato Transport',
     'po' => '33215',
     'commodity' => 'RARE',
     'label' => 'PRODUCE',
  )),
))

But just can't seem to get it right, I believe it has something to do with [0] being an int instead of varchar but I have no idea....

回答1:

The output in your question is created by var_export which represents the data of the object as an array. But don't get mislead by that, it's in fact an object.

Object properties are accessed by this syntax:

$obj->property

In your case the property is named 0 which is hard for PHP to deal with in plain code as it's not a property name you could write right away like this:

$obj->0

Instead, you need to tell the PHP parser what the name is by enclosing it into {}:

$obj->{0}

You can then traverse further on to access the type property of 0:

$obj->{0}->type

Hope this is helpful, the question comes up from time to time, this is a related one with more related links: How do I access this object property?.

The PHP Manual has this documented, but not very obvious on the Variable variables entry:

In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.



回答2:

Have you tried:

<?php
    if (property_exists($obj, 'type')) { 
        // Do something 
    }
?>


标签: php oop object