Access a single object inside an array

Events happening in the community are now at Drupal community events on www.drupal.org.
alanburke's picture

Hi all,
Some more basic PHP help requested [I know, I really should go to a PHP forum for this stuff :-)]

For a vocabulary with only one term allowed, taxonomy module can return you that information via
http://api.drupal.org/api/function/taxonomy_node_get_terms_by_vocabulary
.
That returns something like this

<?php
#
... (Array, 1 element)

    *
     
125 (Object) stdClass
          o
            tid
(String, 3 characters ) 125
          o
            vid
(String, 1 characters ) 3
          o
            name
(String, 6 characters ) Dublin
          o
            description
(String, 0 characters )
         
o
            weight
(String, 1 characters ) 0
?>

which is basically one object, the term, inside an array.
Because its a keyed array, with the tid as the key, I can't just go
<?php
return $county[0]->name;
?>

I'm guessing there is a better way to access that data rather than what I currently do, which is a bit convoluted, to say the least.

<?php
      $county
= taxonomy_node_get_terms_by_vocabulary($vars['node'],3);
       foreach (
$county as $item) {
      
$countyname = $item->name;
       }
?>

Any input appreciated?

Regards
Alan

Comments

try this

Dublin Drupaller's picture

If the snippet is for use in a theme, you could try this..

<?php
foreach ($node->taxonomy as $term) {
$countyname = $term->name
 
}
?>

I haven't tested that....it's just a guess...but, if it works, it avoids the need to make a database query using taxonomy_node_get_terms_by_vocabulary....i,.e. it assumes the taxonomy module has already queried the database for all the terms associated with the node..allowing you to pull the term name value straight out of the $node-taxonomy array.

dub

Good idea

alanburke's picture

Hi Dub
Yep, that would work if I had only one vocabulary [with a single term].
The problem is that I have multiple vocabularies associated with the node,
and want fine grained control of the output [different vocabularies displayed differently].

My solution above works - in that I get the result I want.
It just feels like there is a might be a more direct way to do it, that I don't know about!

Thanks,
Alan

vocab id

Dublin Drupaller's picture

Ah. I see what you mean. If you already know the vocabulary id, this might work..

<?php
foreach ($node->taxonomy as $term) {
  if (
$term->vid == 3) {   // filter terms in vocabulary with ID 3
 
$countyname = $term->name
 
}
}
?>

Winner alright!

alanburke's picture

Great work Dub!

That works really well.
A much smarter way that I had of getting at that data.

Regards
Alan

Perfect

Kesavamoorthi's picture

foreach ($query as $term) {
$value = $term->field_subscription_expiration_value;
}

It works damn good for me

Ireland

Group notifications

This group offers an RSS feed. Or subscribe to these personalized, sitewide feeds: