如何以特定格式获取JSON响应?

时间:2016-01-21 15:37:33

标签: php json laravel

我试图测试一个模块,我需要重新创建一个json,如下所示:

$billing_info['billing']->customer_id
$billing_info['billing']['source']->exp_year

我尝试按以下方式重新创建它:

$arr = json_encode(['id'=>'card_17LHmCI49Oxjrr81SringkGq', 'exp_year'=>2018, 'exp_month' => 07, 'funding' => 'credit', 'brand' => 'Visa', 'last4' => '4242']);

$customer = json_encode(['customer_id' => 'cus_7aSheljul3mkAB', 'source' =>json_decode($arr)]);

但我无法拨打dd($billing_info['billing']->customer_id);

所需的JSON响应如下:

[
  "billing" => [
    {"customer_id": 12 }
    "source" => {
      "exp_year": 2018
      "exp_month": 7
      "funding": "credit"
      "brand": "Visa"
      "last4": "4242"
    }
  ]
]

1 个答案:

答案 0 :(得分:1)

$customer = new stdClass();
$customer->customer_id=1;
$customer->source=new stdClass();
$customer->source->exp_year=2018;
$billing_info = array('billing'=>$customer);

UPDATE1:

刚才意识到你想要的是不可能的:

$billing_info['billing']->customer_id
$billing_info['billing']['source']->exp_year

在第1行,您假设$ billing_info [' billing']是一个对象,而在第二行,您认为它是一个数组。请决定你喜欢哪一个:

$billing_info['billing']->customer_id
$billing_info['billing']->source->exp_year

$billing_info['billing']['customer_id']
$billing_info['billing']['source']->exp_year

可选[' exp_year']也是可能的

UPDATE2:

请包含一个有效的json!您可以在此处查看:http://jsonlint.com/