PHP基于键显示数组中对象的值

时间:2017-11-15 11:13:22

标签: php arrays object drupal-7

我有以下数组,其中包含对象和数组。如何根据键获取特定值(对于每个对象)? 我已经过测试,阵列正在显示(见下文),但我无法隔离这个名称"价值根据需要。

我已尝试使用以下代码获取名称值:

case 'field_prgm_housing' :
$node = 'field_color';
$tids =  field_get_items('node', $node, $key, $node->language);
$terms = taxonomy_term_load_multiple(array(), array('tid' => $tids));
$nameonly = $terms->[0]->name[0];
return = $nameonly;
break;      
Colors (Array, 2 elements)
    12 (Object) stdClass
      tid (String, 2 characters ) 12
      vid (String, 1 characters ) 3
      name (String, 9 characters ) Blue
      description (String, 0 characters )
      format (String, 13 characters ) filtered_html
      weight (String, 1 characters ) 0
      vocabulary_machine_name (String, 15 characters ) colors
      rdf_mapping (Array, 5 elements)
      path (Array, 1 element)
    13 (Object) stdClass
      tid (String, 2 characters ) 13
      vid (String, 1 characters ) 3
      name (String, 8 characters ) Green
      description (String, 0 characters )
      format (String, 13 characters ) filtered_html
      weight (String, 1 characters ) 0
      vocabulary_machine_name (String, 15 characters ) colors
      rdf_mapping (Array, 5 elements)
      path (Array, 1 element)

2 个答案:

答案 0 :(得分:2)

Try this


    $node = 'field_color';
    $tids =  field_get_items('node', $node, $key, $node->language);
    $terms = taxonomy_term_load_multiple(array(), array('tid' => $tids));

    //loop all the values and get the require value
   $name = array();
    foreach($terms as $term){
          $name[] = $term->name;
    }
    return $name;

答案 1 :(得分:0)

$terms->[0]的意思是什么?

$terms是一个数组,因此您必须通过指定要获取的索引来访问它,例如:$terms[12], $terms[13] ...

该数组的元素是对象,所以当你得到一个时,你必须使用“ - >”运算符来获取它的字段(或方法)。

所以它必须像:

$nameonly = $terms[12]->name;
$nameonly = $terms[13]->name;

或者你可以像@kranthi建议的那样迭代所有数组项。