所以我被难住了,我不确定我将如何继续这个例如,让我们只使用 books.com
作为 URL,假设来自 URL 的 JSON 响应是
[{"title":"first_title","description":"second_title"},
{"title":"second_title","description":"second_description"}]
我将如何在不知道确切有多少标题的情况下打印所有标题(只是标题)。
我知道我需要遍历 JSON,但我不确定如何,如果我能得到任何非常棒的指导。
你应该更熟悉json_decode()和foreach()。首先,您需要解码 json(在本例中为数组),然后遍历所有元素。
工作代码示例:
<?php
$json = '[{"title":"first_title","description":"second_title"},
{"title":"second_title","description":"second_description"}]';
$jsonArray = json_decode($json,true);
foreach($jsonArray as $entry) {
echo $entry['title'].'<br>';
}
输出:
first_title
second_title
这个关键是使用 json_decode 实际将 JSON 响应转换为 PHP 关联数组,然后循环访问它。
// Convert the JSON into a PHP associative Array
$response = json_decode($curlResponse,true);
// Loop through the array
foreach ($response as $value) {
echo $value['title'];
echo '<br/>';
}