0

I have this array called $locations and this is what it produces if I use print_r:

Array
(
    [0] => stdClass Object
    (
        [term_id] => 40
        [name] => California
        [slug] => california
        [term_group] => 0
        [term_taxonomy_id] => 41
        [taxonomy] => location
        [description] =>
        [parent] => 0
        [count] => 6
     )
) 

What I need to get from this array is California only, but I can't figure out what variable produces that. I tried $locations->name and $locations[name] but none of those work.

4
  • 4
    try $locations[0]->name Commented Mar 21, 2014 at 15:00
  • refer to hsz's answer if your array has multiple objects Commented Mar 21, 2014 at 15:01
  • Thank you! that did the trick. So i should just ignore the stdClass Object part right? Thats what made me get confused. Commented Mar 21, 2014 at 15:08
  • No, see, you have an object inside an array, so that object is the first element of the array. this means you have to access the object first (i.e. $locations[0]) and then perform the object manipulation. If you don't intend to have multiple objects in one variable, then really you should be making $locations just the object, not an array of objects. Commented Mar 21, 2014 at 15:12

2 Answers 2

3

$locations seems to be an array (with 1 value, that is an object), so:

$locations[0]->name
Sign up to request clarification or add additional context in comments.

Comments

0

Just try with:

$data = array( /* your data */ );

foreach ($data as $obj) {
  $name = $obj->name; // California - and others in the nest steps 
                      // if array contains more elements
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.