检查作为对象一部分的数组是否为空

时间:2013-10-08 15:16:19

标签: php drupal if-statement

这是在Drupal中,但应该适用于普通的PHP。

field-event-address是一个位于$entity_fetched下的数组。

<?php if ($entity_fetched->field-event-address != "") echo $entity_fetched->field-event-address['und']['0']['value']; ?>

出于某种原因,当我这样做时,如果我离开['und']['0']['value'],我会收到此错误:

Notice: Undefined property: stdClass::$field in eval() (line 7 of /opt/staging/contitemp/public_html/sites/all/modules/rules/modules/php.eval.inc(125) : eval()'d code).
Notice: Use of undefined constant event - assumed 'event' in eval() (line 7 of /opt/staging/contitemp/public_html/sites/all/modules/rules/modules/php.eval.inc(125) : eval()'d code).
Notice: Use of undefined constant address - assumed 'address' in eval() (line 7 of /opt/staging/contitemp/public_html/sites/all/modules/rules/modules/php.eval.inc(125) : eval()'d code).

如果我把它留在了这个错误:

Parse error: syntax error, unexpected '[', expecting ',' or ';' in /opt/staging/contitemp/public_html/sites/all/modules/rules/modules/php.eval.inc(125) : eval()'d code on line 7

我正在尝试创建一个if语句来检查对象下的数组是否为空,如果不是,则回显数组内容。

我真的对这个问题感到头疼 - 我应该能够检查一个数组是否为空,如果它在一个物体下面,对吗?

2 个答案:

答案 0 :(得分:1)

-符号不能在PHP中的变量名中使用。因为你正在获得语法错误(或当PHP试图理解你的意思时未定义的常量)。

相反,您可以将名称更改为$entity_fetched->fieldEventAddress(它仍然可读,现在它是正确的。)

答案 1 :(得分:0)

对于Drupal,你真的应该使用实体元数据包装器。

所以你的代码应该是这样的:

$wrapper = entity_metadata_wrapper('entity_type', $fetched_entity);
$value = $wrapper->field_name->value();
if (!empty($value)) echo $value;

您可以在此处找到有关实体元数据包装器的更多信息: https://drupal.org/node/1021556

相关问题