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

pcr*_*x20 4 php arrays drupal drupal-taxonomy

我试图使用以下代码从术语中获取termId:

  $term = taxonomy_get_term_by_name($address_string); 
  $termId = $term[0]->tid;
Run Code Online (Sandbox Code Playgroud)

有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)
Run Code Online (Sandbox Code Playgroud)

非常感谢,

PW

Vla*_*ban 6

可能是最好的选择

$termid = key($term);
Run Code Online (Sandbox Code Playgroud)

它将输出30

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

key()函数只返回内部指针当前指向的数组元素的键.它不会以任何方式移动指针.如果内部指针指向超出元素列表末尾或数组为空,则key()返回NULL.

打电话可能更好

reset($term);
Run Code Online (Sandbox Code Playgroud)

在调用关键功能之前

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

其他选项如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;
}
Run Code Online (Sandbox Code Playgroud)