【问题标题】:PHP: How to print sub values from multi-level array (Stripe object)PHP:如何从多级数组中打印子值(条带对象)
【发布时间】:2020-03-02 04:50:57
【问题描述】:

我得到以下从检索 Stripe 会话 ID 中返回的对象(该对象称为 $order)。

我可以使用例如从第一个对象级别打印值print_r($order->id);

如何打印第二级的值,例如金额或货币?
我试过print_r($order->display_items->amount);print_r($order->display_items['amount']);

PHP:

Stripe\Checkout\Session JSON: { 
    "id": "some_id", 
    "object": "checkout.session", 
    "billing_address_collection": null, 
    "cancel_url": "some_url", 
    "client_reference_id": null, 
    "customer": "some_id", 
    "customer_email": null, 
    "display_items": [{
        "amount": 2990, // this is what I need
        "currency": "eur", // this is what I need
        "custom": {
            "description": null, 
            "images": null, 
            "name": "some_product"
        },
        "quantity": 1, 
        "type": "custom"
    }], 
    "livemode": false, 
    "locale": "en", 
    "mode": "payment", 
    "payment_intent": "some_id", 
    "payment_method_types": [ "card" ], 
    "setup_intent": null, 
    "submit_type": null, 
    "subscription": null, 
    "success_url": "some_url"
}

更新: 如果我使用print_r($order->display_items);,我会得到以下信息。我可以将它分配给一个数组然后从那里打印(如果没有其他解决方案)?

Array ( [0] => Stripe\StripeObject Object ( [amount] => 2990 [currency] => eur [custom] => Stripe\StripeObject Object ( [description] => [images] => [name] => some_product ) [quantity] => 1 [type] => custom ) )

非常感谢。

【问题讨论】:

  • 可能遗漏了什么,但json_decode() 不能在这里工作吗?
  • @mtr.web:谢谢。我不需要整个对象,只需要它的特定值。例如。我想将金额用于该页面上的字段。我可以用 json_decode 实现吗?
  • 超级低效,但json_decode($yourStripeJsonVar)['display_items']['amount'] 应该可以工作
  • @mtr.web:再次感谢。如果这不是一个好方法,你会建议什么?从整个对象中,我只需要 4 或 5 个值。另外,如何使用上述方法打印金额?我试过 print_r(json_decode($order)['display_items']['amount']);
  • @Jdub:谢谢。那也不行。如果我使用 $order->display_items 我会得到所有的值,但我不能从中选择特定的子值。

标签: php arrays multidimensional-array stripe-payments


【解决方案1】:

print_r($obj->display_items[0]->amount);

请确保您的 JSON 有效 :) https://jsonlint.com/

【讨论】:

  • 这正是我所需要的,而且效果很好。非常感谢!
  • 非常感谢!这对我帮助很大。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-19
  • 1970-01-01
  • 2020-04-11
  • 1970-01-01
相关资源
最近更新 更多