4

I have the following associative array called $woo_post_category:

array(1) { [0]=> object(stdClass)#5839 (10) { ["term_id"]=> int(796) ["name"]=> string(20) "Womens Comfort Bikes" ["slug"]=> string(20) "womens-comfort-bikes"

I'm attempting to loop through the array and pull out the value association for the name key. I have the following code:

foreach($woo_post_category as $key_category => $value_category) {
        if ( $key_category == 'name') {
            echo 'Product is in Category:' . ' ' . $value_category;
        }
} 

I get the error :

PHP Catchable fatal error: Object of class stdClass could not be converted to string

Can anyone point out the issue here, thanks

3
  • You can use array_key_value()... Commented Dec 21, 2015 at 11:25
  • $value_category is object of stdClass and you are trying to echo it. try $value_category->term_id. Commented Dec 21, 2015 at 11:27
  • Can you post the full array output? Commented Dec 21, 2015 at 13:29

3 Answers 3

2

Try this:

foreach($woo_post_category[0] as $key_category => $value_category) {
    if ( $key_category == 'name') {
        echo 'Product is in Category:' . ' ' . $value_category;
    }
}

$woo_post_category is Array with one element, not an Object.

So, $woo_post_category[0] is first element of array, and this is your object.

When you use foreach, $key_category is key of array (0), and $value_category is value of first element, and it is stdClass.

So, when you try to run

if ( $key_category == 'name') {

, you compare stdClass ($key_category) and 'name'. And that why you got this error.

Sign up to request clarification or add additional context in comments.

Comments

1

In your case it seems, $value_category would come as object.

so you would get data in following manner

$value_category->name

$value_category->term_id

so you can correct the condition to make your script working.

in case need more help, please pass me script.

Thanks Amit

Comments

1

You've an associative array and not the single dimensional array so your if condition would be like as

foreach($woo_post_category as $key_category => $value_category) {
        if ( key_exists('name',$value_category)) {
            echo 'Product is in Category:' . ' ' . $value_category->name;
        }
} 

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.