简体   繁体   中英

Iterate through PHP object with foreach (Stripe Customer)

I am trying to iterate over the metadata stored in a Stripe customer object.

I can count the number of items:

echo count($matchUser->data[0]->metadata);

Which gives me '2' as expected. But:

foreach($matchUser->data[0]->metadata as $key => $value) {
    echo $key;
    echo $value;
    echo "hello";
}

returns nothing.

Var dump of the metadata is as follows:

object(Stripe\StripeObject)#67 (2) { ["testitem"]=> string(5) "hello" ["password_hash"]=> string(6) "myhash" }

Try the method

public function __toArray($recursive = false)
{
    if ($recursive) {
        return Util\Util::convertStripeObjectToArray($this->_values);
    } else {
        return $this->_values;
    }
}

like this:

$matchArray = $matchUser->__toArray();

to a deeper understanding of what methods are available please take a look at this url:

https://github.com/stripe/stripe-php/blob/master/lib/StripeObject.php

hope it helps

I know this question is a couple of months old and it already has an accepted answer. I think there is a better approach to it though.

I think the developers of the PHP library for the Stripe API prefix some methods with __ (double underscore) to indicate the method is protected or private, which is an old convention from the times when method visibility was not a thing in PHP. Now the __ prefix is reserved for magic methods as stated in PHP: Magic Methods - Manual :

PHP reserves all function names starting with __ as magical.

After taking a closer look to the StripeObject class I think the jsonSerialize method that is defined as below is a better choice.

public function jsonSerialize()
{
    return $this->__toArray(true);
}

You can use it like this:

$matchUserArray = $matchUser->jsonSerialize();

// Output "hello" 
echo $matchUserArray['data'][0]['metadata']['testitem']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM