简体   繁体   English

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

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

I have the following array which contains both objects and arrays. 我有以下包含对象和数组的数组。 How do I get only the specific values (for each object) based on their keys? 如何仅基于键的值获得每个对象的特定值? I've tested and the array is displaying (see below) but I cannot isolate the 'name" value as needed. 我已经测试过并且该数组正在显示(请参见下文),但是我无法根据需要隔离“名称”值。

I have tried the following code to get the name value: 我尝试了以下代码来获取名称值:

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;

What $terms->[0] suppose to mean? $terms->[0]应该是什么意思?

$terms is an array, so you have to access it by specifying the index you want to get, like: $terms[12], $terms[13] ... $terms是一个数组,因此您必须通过指定要获取的索引来访问它,例如: $terms[12], $terms[13] ...

Elements of that array are object so when you get one you have to use "->" operator to get it's field (or method). 该数组的元素是对象,因此当您获得一个数组时,必须使用“->”运算符来获取它的字段(或方法)。

So it has to be like: 所以它必须像:

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

Or you can iterate trough all the array items, as @kranthi suggested. 也可以按照@kranthi的建议遍历所有数组项。

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

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