如何从包含对象的数组中获取对象的元素


How to get an element of an object from an array containing the object

这是一个来自Stripe支付网关的响应数组:

$response = Array ( [deleteCardAccount] => Stripe'Card Object ( [_opts:protected] => Stripe'Util'RequestOptions Object ( [headers] => Array ( ) [apiKey] => sk_test_erwppHN9ibdfgdfg0CesaOwnDy ) [_values:protected] => Array ( [id] => card_18SwerIsEZ1YjoOMVAFRLA [currency] => usd [deleted] => 1 ) [_unsavedValues:protected] => Stripe'Util'Set Object ( [_elts:Stripe'Util'Set:private] => Array ( ) ) ...

上面的数组包含对象"Stripe'Card object",我想获得元素[_values:protected]的值,这是一个数组。

将对象强制转换为数组

$nasty_array = (array)$response['deleteCardAccount'];
print_r($nasty_array); 

我得到这个数组它的键以星号开头

Array ( [*_opts] => Stripe'Util'RequestOptions Object ( [headers] => Array ( ) [apiKey] => sk_test_wejYbwerCerwesaOefg ) [*_values] => Array ( [id] => card_18SwerIsEZ1YjoOMVAFRLA [currency] => usd [deleted] => 1 ) [*_unsavedValues] => Stripe'Util'Set Object ( [_elts:Stripe'Util'Set:private] => Array ( ) ) ...

然而当我尝试

print_r($nasty_array[*_opts]);
print_r($nasty_array[*_values]);

我得到

error: Undefined index *_values 
error: Undefined index *_opts  

问题:

  1. 为什么数组中的键以星号开头
  2. 如何访问这些键而不解析
  3. 是否有另一种方法来获取关联数组内部对象的元素?

注意:当我手动创建一个数组,其中的键以星号开始,然后我可以访问这样的键没有问题,但由于某种原因,我不能访问类似的键时,将对象转换为一个数组;

可以将数组中的对象捕获到变量中,而不需要强制转换;

$captured_object = $response['deleteCardAccount'];

然后可以使用"箭头"符号简单地引用捕获对象的元素:

print_r($captured_object->id);    
print_r($captured_object->currency);
print_r($captured_object->deleted);

或者更简单的对象可以通过混合数组符号和箭头符号直接引用:

print $response['deleteCardAccount']->id;
print $response['deleteCardAccount']->currency
print $response['deleteCardAccount']->deleted;

此方法适用于条带响应对象,但尚未对具有受保护属性的其他对象进行过测试。