作者:450651324_43c723 | 来源:互联网 | 2024-12-01 17:28
在处理API返回的数据时,经常需要从复杂的JSON结构中提取特定的信息,如产品标题。下面是一个示例,展示了如何从给定的JSON响应中提取所需的产品标题。
首先,我们已经获取了如下形式的数据:
object(stdClass)[1]
public 'status' => string 'ok' (length=2)
public 'data' =>
object(stdClass)[3]
public 'sort_data' =>
object(stdClass)[2]
public 'sort_column' => string 'order_item_id' (length=13)
public 'sort_order' => string 'asc' (length=3)
public 'pager' =>
object(stdClass)[4]
public 'page' => int 1
public 'item_per_page' => int 50
public 'total_page' => int 1
public 'total_rows' => int 21
public 'form_data' =>
array (size=0)
empty
public 'items' =>
array (size=21)
0 =>
object(stdClass)[5]
public 'order_item_id' => int 323360064
public 'order_id' => int 111179028
public 'variant' =>
object(stdClass)[6]
public 'id' => int 17586275
public 'seller_id' => int 186764
public 'site' => string 'digikala' (length=8)
public 'is_active' => boolean true
public 'is_archived' => boolean false
public 'title' => string 'Mug' (length=115)
public 'product' =>
object(stdClass)[7]
public 'id' => int 3634323
public 'category_id' => int 6289
public 'title' => string 'Mug model series' (length=40)
public 'shipping_nature_id' => int 1
...
上述数据是通过以下PHP代码从服务器获取的:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'site_url',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json, application/json;charset=UTF-8',
'Authorization: {{token}}'
),
));
$respOnse= curl_exec($curl);
var_dump(json_decode($response));
若想从这个JSON响应中提取产品标题,如 public 'title' => string 'Mug model series'
,可以通过将 json_decode()
的第二个参数设置为 true
,以确保返回的是数组而非对象,从而更容易地进行遍历和访问:
$respOnseArray= json_decode($response, true);
$productTitle = $responseArray['data']['items'][0]['product']['title'];
echo 'Product Title: ' . $productTitle;
这样,你就可以轻松地访问到产品标题了。如果需要访问其他字段,也可以采用类似的方式进行操作。