user1269625
user1269625

Reputation: 3209

How to access data from an array of objects?

I have this line of code:

print_r(get_the_terms( $_product->id, 'product_cat'));

which returns:

Array ( [0] => stdClass Object ( [term_id] => 67 [name] => Paintings [slug] => paintings [term_group] => 0 [term_taxonomy_id] => 67 [taxonomy] => product_cat [description] => [parent] => 0 [count] => 44 ) [1] => stdClass Object ( [term_id] => 13 [name] => Small [slug] => small [term_group] => 0 [term_taxonomy_id] => 13 [taxonomy] => product_cat [description] => [parent] => 0 [count] => 15 ) )

what I am trying to get is [name] => Paintings so I can create another array like so:

$array[get_the_terms( $_product->id, 'product_cat')->name] = $_product->get_title()

$_product->get_title() is "A Quiet Day"

expected output Array ( [Paintings] => A Quiet Day )

If I do this:

$array[] = $_product->get_title();

the output is

Array ( [0] => A Quiet Day )

I am just trying to replace the 0 with Paintings

Upvotes: 0

Views: 88

Answers (1)

Jessica
Jessica

Reputation: 7005

$array['Paintings'] = $_product->get_title();

If you want the array to have specific keys, specify them...

The problem may be that it looks like the class you're storing that name in is not properly defined. Are you storing it in the session?

Your get_the_terms() function also appears to return more than one object, so you will not be able to chain ->name off it. You'll need to select the right one.

You need to make your code and question more readable.

Upvotes: 2

Related Questions