从Json对象为stripe设置PHP变量



PHP学生第一次使用json。Stripe正在使用Json发送数据,我正在尝试为我的PHP变量设置特定的对象。例如,我如何将Json结果中的"subscriptions"->"amount"中的变量设置为"5000":

            object: "customer",
            created: 1410050969,
            id: cus_4jMblEOo2y84j6,
            livemode: false,
            description: "payinguser@example.com",
            email: "sample24@gmail.com",
            delinquent: false,
            metadata:
            {}
            subscriptions::
            {
                object: "list"
                total_count: 1
                has_more: false
                url: "/v1/customers/cus_4jMblEOo2y84j6/subscriptions"
                data:
                [
                    {
                        id: sub_4jMbSoTXxUBHd0
                        plan:
                        {
                            interval: "year",
                            name: "Website Hosting",
                            created: 1409981699,
                            amount: 5000,
                            currency: "usd",
                            id: webhosting,
                            object: "plan",
                            livemode: false,
                            interval_count: 1,
                            trial_period_days: null,
                            metadata:
                            {},
                            statement_description: null
                        },
                        count:1
            }

我最好的失败尝试:

    $amount = customer->subscriptions->data->plan->amount;
    $amount = $event_json->customer->subscriptions->data->plan->amount;
    $amount = subscriptions->data->plan->amount;
    $amount = $event_json->subscriptions->data->plan->amount;

非常感谢在这种情况下有帮助的任何想法或一般json/php参考!

amount位于订阅的data数组中,因此它看起来像:

$customer->subscriptions->data[0]->plan->amount = 5000;

因此,这里的关键是data是一个订阅对象数组,因此您需要确定要设置值的对象中的哪一个-如果只有一个,则可以使用密钥0。如果有多个,则需要对它们进行筛选以获得所需的密钥(除非您知道特定的密钥,在这种情况下可以使用该密钥而不是0)。例如:

$subid = 'sub_4jMbSoTXxUBHd0';
foreach ($customer->subscriptions->data as $k => $sub) {
   if ($sub->id === $subid) {
     $customer->subscriptions->data[$k]->plan->amount = 5000;
     break;
   }
}

另一个更容易处理的事情是将所有JSON对象作为数组保留在PHP端,这样您就不需要根据类型进行不同的访问。为此,可以使用json_decode:的第二个参数

// by passing true as the second arg js objects get converted to associative arrays
$customer = json_decode($jsonString, true);
$subid = 'sub_4jMbSoTXxUBHd0';
// now we can use array notation for objects instead of ->
foreach ($customer['subscriptions']['data'] as $k => $sub) {
   if ($sub->id === $subid) {
     $customer['subscriptions']['data'][$k]['plan']['amount'] = 5000;
     break;
   }
}

最新更新