【问题标题】:How do I access this JSON information (PHP)? [duplicate]如何访问此 JSON 信息 (PHP)? [复制]
【发布时间】:2018-07-20 18:29:56
【问题描述】:

我无法访问订单数组中的内容。我目前这样做无济于事,我想知道我做错了什么:

$json 对象是来自 rest api 的 json 响应。

$orderData = $json['orders'];
  foreach($orderData['orders'] as $order){
}

{  
   "errors":[  

   ],
   "orders":[  
      {  
         "note":"",
         "estimated_shipping_fee":"0.00",
         "payment_method":"PAY_CYBERSOURCE",
         "escrow_amount":"12.95",
         "message_to_seller":"",
         "shipping_carrier":"Singpost - Normal Mail",
         "currency":"SGD",
         "create_time":1532064559,
         "pay_time":1532064618,
         "recipient_address":{  
            "town":"",
            "city":"",
            "name":"Teo",
            "district":"",
            "country":"SG",
            "zipcode":"41253",
            "full_address":"In some street somewhjere",
            "phone":"23154991",
            "state":""
         },
         "days_to_ship":3,
         "tracking_no":"",
         "order_status":"SHIPPED",
         "note_update_time":0,
         "update_time":1532082525,
         "goods_to_declare":false,
         "total_amount":"12.95",
         "service_code":"",
         "country":"SG",
         "actual_shipping_cost":"",
         "cod":false,
         "items":[  
            {  
               "weight":1.0,
               "item_name":"ABC",
               "is_wholesale":false,
               "item_sku":"5123433123",
               "variation_discounted_price":"12.95",
               "variation_id":0,
               "variation_name":"",
               "item_id":1126534500,
               "variation_quantity_purchased":1,
               "variation_sku":"",
               "variation_original_price":"12.95"
            }
         ],
         "ordersn":"3589290984539"
      }
   ]
}

尝试直接访问变量,例如 json['orders'][0]['payment_method'] 不起作用。

【问题讨论】:

  • 你用过json_decode?你有错误吗?
  • 当您使用json_decode 时(当然假设您确实使用了json_decode),将结果转换为关联数组的选项默认设置为FALSE。所以如果你只是做了这样的事情:$json = json_decode($theResponse);,你将无法使用像$json['orders'][0]['payment_method']这样的数组语法访问结果
  • $responseData = json_decode($server_output, TRUE);我将此参数指定为 true :(

标签: php json rest


【解决方案1】:

使用 json_decode() 将其从 json 转换为数组;那么您可以轻松访问它,如果您想使用 jquery 访问,那么只需使用 jQuery.parseJSON(); 转换它的对象;

【讨论】:

  • 这真的只是一个评论
  • $jsondata='[{"cid":"1234","city":"value1","district":"value2","state":"value3"}]'; // json 格式数据 $array = json_decode($jsondata); // json decode //输出数组( [0] => stdClass Object ( [cid] => 1234 [city] => value1 [district] => value2 [state] => value3 ) )
  • 那是什么?
【解决方案2】:

只需使用 json_decode 检索对象,然后使用 $obj->note 或者您可以将其转换为数组:$array = get_object_vars($obj); 就像在 this answer 中一样。

【讨论】:

  • 这真的只是一个评论
猜你喜欢
  • 1970-01-01
  • 2018-11-13
  • 1970-01-01
  • 1970-01-01
  • 2019-03-02
  • 1970-01-01
  • 2013-03-18
  • 1970-01-01
  • 2022-07-21
相关资源
最近更新 更多