簡體   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