简体   繁体   English

如何从嵌套的 JSON 中获取 URL

[英]How to get URL from nested JSON

I have the following JSON from which I need to extract the URL of the icon in PHP:我有以下 JSON,我需要从中提取 PHP 中图标的 URL:

product 
  id    3
  name  "ETC Source 4 19deg"
  type  "Product"
  tax_class_id  2
  rental_revenue_group_id   1
  sale_revenue_group_id 2
  created_at    "2017-10-02T10:50:32.239Z"
  updated_at    "2017-10-02T16:48:44.844Z"
  custom_fields {}
  product_group {…}
  tax_class {…}
  icon  
    id  1
    iconable_id 3
    iconable_type   "Item"
    image_file_name "Source_4_fixed.jpg"
    url "https://s3.amazonaws.com/current-rms/899701e0-898a-0135-ef0d-0a9ca217e95b/icons/1/original/Source_4_fixed.jpg"
    thumb_url   "https://s3.amazonaws.com/current-rms/899701e0-898a-0135-ef0d-0a9ca217e95b/icons/1/thumb/Source_4_fixed.jpg"
    created_at  "2017-10-02T16:48:44.747Z"
    updated_at  "2017-10-02T16:48:44.747Z"

I have used the following to get the top level info:我使用以下内容来获取顶级信息:

$ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);

    $data = json_decode($response);

    return $data;

public function getProduct( $id )
{
    $data = $this->query('products/' . $id);
    return $data->product;
}

$html .= '<div class="row">';
    $html .= 'Product Name is:' . $product->name;
    $html .= '</div>';
    echo $html;

Any help appreciated.任何帮助表示赞赏。

Chris克里斯

What you posted in your question is not a JSON format but it looks like a striped one.您在问题中发布的内容不是 JSON 格式,但看起来像条纹格式。 However, to access to an element you just need to down through it like a tree, in your case you want URL so it becomes:但是,要访问一个元素,您只需要像树一样向下遍历它,在您的情况下,您需要URL因此它变为:

product -> icon -> url

And the PHP version:和 PHP 版本:

echo $data->icon->url;

You can also convert the JSON format to an array and then access to elements like this:您还可以将 JSON 格式转换为数组,然后访问如下元素:

{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);
    $data = json_decode($response, TRUE); // passing true parameter
    return $data;
}


echo $data['product']['icon']['url'];

For more explination and examples read those answers of this question ' How do I extract data from JSON with PHP?有关更多说明和示例,请阅读此问题的答案“ 如何使用 PHP 从 JSON 中提取数据? '. '。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM