-1

I´m iteration successfully through a large array that combines arrays and stdClass using the following code:

foreach ($arr as $A) {
        $THIS=$A->w->b;         
}

Here is an example of the array I'm iterating through:

Array
(
     [0] => Array
         (
             [w] => stdClass Object
              (
                 [b] => THIS
         )
     [1] => Array
         (
             [w] => stdClass Object
              (
                 [b] => THIS
         )
     [2] => Array
         (
             [w] => stdClass Object
              (
                 [b] => THIS
         )
     [3] => Array
         (
             [z] => stdClass Object
              (
                 [whatever] => NOT THIS
         )
)

I need to retrieve THIS values from [x] stdClass Object of each array; [0],[1],[2],etc. But I do not need to retrieve values from [z] which has a different key.

Therefore when running the above code I successfully retrieve the desired THISvalues, but I get repeatedly an error when iterating throughout the arrays that do not contain the stdClass object I desire:

PHP Notice: Undefined property: stdClass::

What would be the simplest way through which can I set the iteration to skip certain undesired objects? or set it to skip if the desired object is not present?

1 Answers1

2

The simplest approach is to check that the object parameters exist...

foreach ( $arr as $A )
{
  if( isset( $A['w'] ) )
  {
    $THIS = $A['w']->b;         
  }
}

Edit: You can also check further conditions

foreach ( $arr as $A )
{
  if( is_array( $A ) and isset( $A['w'] ) and is_object( $A['w'] ) and isset( $A['w']->b ) )
  {
    $THIS = $A['w']->b;         
  }
}
Scuzzy
  • 12,186
  • 1
  • 46
  • 46