【问题标题】:Accessing element from standard class object从标准类对象访问元素
【发布时间】:2016-10-25 19:15:34
【问题描述】:

我试图在 Drupal 模块 Viewsphp 中检索一个变量,但我的问题实际上只是访问 stdclass 对象中的嵌套元素。

print_r($data->node_created); // 给出正确的值 1477420603

print_r($data->_field_data->nid->entity->vid); 返回什么都不应该是 31

我做错了什么?

这里是返回数据的摘录:

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

【问题讨论】:

  • 试试这个并告诉我$data->_field_data['nid]['entity']->vid;我可以解释它是否有效

标签: php arrays drupal stdclass


【解决方案1】:

您首先使用对象运算符->。这是您访问对象的属性或方法的方式。这将返回该操作的值。

//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'];

请注意,尽管在您的输出中 [entity] => stdClass Object 实体返回到一个对象,所以您需要返回到 ->

//Full access

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

通常对象具有访问器或getter 方法,即getVid() 方法。不确定这里是否是这种情况,但是您可以访问像$data->getVid(); 这样的数据,这要简单得多,并且可以在底层api发生变化时保护您的代码。值得研究文档或代码。

【讨论】:

  • 感谢 nerdylist - 提供答案和解释。
猜你喜欢
  • 1970-01-01
  • 2014-02-09
  • 2020-11-26
  • 2018-02-17
  • 1970-01-01
  • 2014-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多