簡體   English   中英

如何從嵌套的 JSON 中獲取 URL

[英]How to get URL from nested JSON

我有以下 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"

我使用以下內容來獲取頂級信息:

$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;

任何幫助表示贊賞。

克里斯

您在問題中發布的內容不是 JSON 格式,但看起來像條紋格式。 但是,要訪問一個元素,您只需要像樹一樣向下遍歷它,在您的情況下,您需要URL因此它變為:

product -> icon -> url

和 PHP 版本:

echo $data->icon->url;

您還可以將 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'];

有關更多說明和示例,請閱讀此問題的答案“ 如何使用 PHP 從 JSON 中提取數據? '。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM