我想知道如何连接[und][0][value]。我不想每次都写[und][0][value]。所以我不得不这样做:
<?php
$und_value = $load->field_testimonial_location['und'][0]['value'];
$query = db_select('node','n');
$query->fields('n',array('nid'));
$query->condition('n.type','testimonial','=');
$result = $testimonial_query->execute();
while($fetch = $result->fetchObject()){
$load = node_load($fetch->nid);
// $location = $load->field_testimonial_location['und'][0]['value'];
$location = $load->field_testimonial_location.$und_value;
echo $location;
}
但它不起作用。它输出数组那么这个问题有任何IDA吗?我该怎么办?此处为完整代码
为什么不制作一些函数,将节点字段作为参数并返回其值
function field_value($field){
return $field['und'][0]['value'];
}
类似的东西(未测试)。
但若你们不想使用这个函数,试着使用大括号,比如:
$location = $load->{field_testimonial_location.$und_value};
这应该有效。。。
扩展米兰发布的答案,使函数更通用
function field_value($field, $index = 0 ){
return $field['und'][$index]['value'];
}
有时您有多值字段,在这种情况下,您还必须传递值的索引。例如
$field['und'][3]['value'];
请不要使用这样的缩写,它们不适合所有情况,最终会破坏您的代码。
相反,已经有一种工具可以用更简单的语法创建自定义代码:实体元数据包装器。
基本上,而不是
$node = node_load($nid);
$field_value = $node->field_name['und'][0]['value'];
然后你可以做一些类似的事情
$node = node_load($nid);
$node_wrapper = entity_metadata_wrapper('node', $node);
$field_value = $node_wrapper->field_name->value();
使用节点包装器,您还可以设置节点的值,这更容易,甚至可以在多语言环境中工作,无需首先获取语言($node->language
)或使用常量(LANGUAGE_NONE
)。
在我的自定义模块中,我经常使用$node
作为节点对象,使用$enode
作为包装器对象。它同样短,仍然知道我在处理哪个对象。