Gags Gags - 7 months ago 12
PHP Question

PHP : Cannot use object of type stdClass as array

i am getting an error while accessing elements if array. Please assist

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"
}
}
}

Answer

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"
    }
  }
}