PHP: update loop through associative array

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 am trying to go through an array and pull out an association of values ​​for a 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 an error message:

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

Can anyone point out the problem here, thanks

+4
source share
3 answers

Try the following:

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 an array with one element, not an object.

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

foreach, $key_category (0), $value_category , stdClass.

,

if ( $key_category == 'name') {

stdClass ($key_category) 'name'. .

+2

, $value_category .

$value_category- >

$value_category- > term_id

, script .

, , script.

Amit

+1

You have an associative array, not a one-dimensional array, so your if condition will look like

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

Source: https://habr.com/ru/post/1621093/


All Articles