1

I am getting an error while accessing elements of an array.

This is my current code:

1st Method::

var_dump($parent_array->info->gcatname);

Error (1st Method)::

<b>Notice</b>:  Trying to get property of non-object

2nd Method::

print_r($parent_array[0]['info']['gcatname']);

Error (2nd Method)::

<b>Fatal error</b>:  Cannot use object of type stdClass as array

Array is as below:

array(1) {
 [0]=>
 array(2) {
  ["is_parent"]=>
    bool(true)
  ["info"]=>
  object(stdClass)#6 (5) {
    ["id"]=>
    string(1) "1"
     ["gcatname"]=>
      string(9) "Swine Flu"
     ["gcatowner"]=>
      string(13) "Vaccine India"
     ["gcatactive"]=>
      string(1) "1"
     ["gcatadded"]=>
      string(19) "2016-05-01 08:30:36"
    }
  }
}
Mr.Web
  • 6,992
  • 8
  • 51
  • 86
Gags
  • 3,759
  • 8
  • 49
  • 96
  • 3
    Square brackets (`[]`) and the key for arrays; `->` for object properties: `print_r($parent_array[0]['info']->gcatname);` – Mark Baker May 01 '16 at 13:59

1 Answers1

2

simply: $parent_array[0]['info']->gcatname

array(1) {
 [0]=> // array(2) stands for the fact that this element with index 0 is an array with the size '2' and it can only be accesses using []
 array(2) {
  ["is_parent"]=>
    bool(true)
  ["info"]=>// object(stdClass) stands for the fact that this element with index 'info' is an array with the size '5' and it can  be accesses using ['info']
  object(stdClass)#6 (5) {// here you have accessed the object now when you wish to access inside this scope you need to use this ->
    ["id"]=>
    string(1) "1"
     ["gcatname"]=>//by using ->gcatname you access the property gcatname of the object
      string(9) "Swine Flu"
     ["gcatowner"]=>
      string(13) "Vaccine India"
     ["gcatactive"]=>
      string(1) "1"
     ["gcatadded"]=>
      string(19) "2016-05-01 08:30:36"
    }
  }
}
Yehia Awad
  • 2,898
  • 1
  • 20
  • 31