gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-10-31 22:44:21 25 4
gpt4 key购买 nike

我尝试使用以下代码从术语中获取 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)

非常感谢,

私服

最佳答案

可能最好的选择是

$termid = key($term);

它将输出30

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

The key() function simply returns the key of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, key() returns NULL.

可能打电话比较好

reset($term);

在调用关键函数之前

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

其他选项如 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;
}

关于php - Drupal - 如何使用 taxonomy_get_term_by_name 从名称中获取术语 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17834400/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com