Drupal-如何使用taxonomy_get_term_by_name从名称中获取术语Id


Drupal - How to get term Id from name with taxonomy_get_term_by_name

我尝试使用以下代码从术语中获取术语Id:

  $term = taxonomy_get_term_by_name($address_string); 
  $termId = $term[0]->tid;

有1个结果,但它显示为术语[30],所以上面的代码不起作用。

我想我可以通过查看第一个元素来访问术语数组,例如$term[0]

我做错了什么?

以下是var_dump($term)的结果:


array (size=1)
  30 => 
    object(stdClass)[270]
      public 'tid' => string '30' (length=2)
      public 'vid' => string '4' (length=1)
      public 'name' => string 'Thonglor' (length=8)
      public 'description' => string '' (length=0)
      public 'format' => string 'filtered_html' (length=13)
      public 'weight' => string '0' (length=1)
      public 'vocabulary_machine_name' => string 'areas' (length=5)

非常感谢,

PW

可能最好的选择是

$termid = key($term);

它将输出30

http://php.net/manual/en/function.key.php

key()函数只返回数组元素的键当前由内部指针指向。它不会移动指针。如果内部指针指向末尾之外元素列表或数组为空时,key()返回NULL。

打电话给可能更好

reset($term);

在调用关键函数之前

重置将内部数组指针重置为第一个元素

另一种选择是如Drupal API手册所说,https://api.drupal.org/comment/18909#comment-18909

/**
 * Helper function to dynamically get the tid from the term_name
 *
 * @param $term_name Term name
 * @param $vocabulary_name Name of the vocabulary to search the term in
 *
 * @return Term id of the found term or else FALSE
 */
function _get_term_from_name($term_name, $vocabulary_name) {
  if ($vocabulary = taxonomy_vocabulary_machine_name_load($vocabulary_name)) {
    $tree = taxonomy_get_tree($vocabulary->vid);
    foreach ($tree as $term) {
      if ($term->name == $term_name) {
        return $term->tid;
      }
    }
  }
  return FALSE;
}