peter300 peter300 - 1 month ago 6
PHP Question

Accessing element from standard class object

I am trying to retrieve a variable in the Drupal Module Viewsphp but my problem is really just accessing nested elements in stdclass object.

print_r($data->node_created); // gives correct value 1477420603

print_r($data->_field_data->nid->entity->vid);
returns nothing should be 31

What am I doing wrong ?

Here is an extract of the data returned:

stdClass Object
(
[node_title] => Denver
[nid] => 31
**[node_created] => 1477420603**
[field_data_body_node_entity_type] => node
[field_data_field_colour_node_entity_type] => node
[field_data_field_type_node_entity_type] => node
[_field_data] => Array
(
[nid] => Array
(
[entity_type] => node
[entity] => stdClass Object
(
**[vid] => 31**
[uid] => 1
[title] => Denver
[log] =>
[status] => 1
[comment] => 2
[promote] => 1
[sticky] => 0
[nid] => 31
[type] => test1
[language] => und

Answer

You are using an object at first use the object operator ->. This is how you access attributes or methods of an object. This will return the value of that operation.

//This is accessing the array stored in _field_data
$data->_field_data;

//Since that is an array now you have to access
//the data in it with the indexes of the array

$data->_field_data['nid']['entity'];

Notice though that in your output [entity] => stdClass Object entity is back to an object so you need to go back to the ->.

//Full access

$data->_field_data['nid']['entity']->vid;

Normally objects have accessors or getter methods ie getVid() methods. Not sure if that is the case here but it you could then access data like $data->getVid(); which is a lot simpler and can protect your code down the road if the underlying api changes. Worth looking into the docs or code for.

Comments