【问题标题】:Drupal - How to get term Id from name with taxonomy_get_term_by_nameDrupal - 如何使用 taxonomy_get_term_by_name 从名称中获取术语 ID
【发布时间】:2013-07-24 12:43:50
【问题描述】:

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

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

有 1 个结果,但它显示为 term[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)

非常感谢,

私服

【问题讨论】:

  • 它工作正常。您的术语在数据库中的 id = 30。
  • array_shift() 是你的朋友

标签: php arrays drupal drupal-taxonomy


【解决方案1】:

也许最好的选择是

$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;
}

【讨论】:

  • 谢谢,我确实使用了:$inner = reset($term); $termId = $inner->tid;
猜你喜欢
  • 1970-01-01
  • 2017-09-20
  • 1970-01-01
  • 2017-07-26
  • 1970-01-01
  • 2017-09-05
  • 1970-01-01
  • 1970-01-01
  • 2022-06-23
相关资源
最近更新 更多