You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP使用cURL调用API如何提取所有索引下的title与artist->name字段值

你拿到的$decoded数组中,所有歌曲数据都存储在data子数组里,直接遍历这个子数组即可批量提取目标字段,修改后的完整代码如下:

$ch = curl_init();
$url = "https://api.deezer.com/search?q=broken%20strings";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$resp = curl_exec($ch);
if($e = curl_error($ch)){
    echo $e;
} else {
    $decoded = json_decode($resp, true);
    // 先判断data字段是否存在,避免接口异常时报错
    if (isset($decoded['data']) && is_array($decoded['data'])) {
        foreach ($decoded['data'] as $item) {
            $title = $item['title'] ?? '无标题';
            $artistName = $item['artist']['name'] ?? '无艺术家信息';
            // 这里可以根据需求处理两个字段,比如打印、存入数组等
            echo "歌曲名:{$title},艺术家:{$artistName}\n<br>";
        }
    }
}
curl_close($ch);

补充逻辑说明:

  • 接口返回的所有歌曲条目都在data层级下,直接遍历该数组就能拿到全部索引的内容,不需要单独指定索引值
  • 代码中加入了??判空操作,避免部分返回条目字段缺失导致PHP抛出警告
  • 如果需要把提取结果留存后续使用,可以在循环外声明一个空数组,循环内把每一组title和artistName写入该数组即可。

内容的提问来源于stack exchange,提问作者hokage minato

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 00:54:00