繁体   English   中英

PHP根据键显示数组中对象的值

[英]PHP Display Values from Object within an Array Based on Key

我有以下包含对象和数组的数组。 如何仅基于键的值获得每个对象的特定值? 我已经测试过并且该数组正在显示(请参见下文),但是我无法根据需要隔离“名称”值。

我尝试了以下代码来获取名称值:

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)
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;

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

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

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

所以它必须像:

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

也可以按照@kranthi的建议遍历所有数组项。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM