PHP Curl Json:多个输出

我目前正在尝试在变量中获取JSON解码输出的每个标题


这就是对我有用的卷曲


$curl = curl_init();

curl_setopt_array($curl, array(

    CURLOPT_URL => 'http://api.irail.be/disturbances/?format=json&lang=nl',

    CURLOPT_RETURNTRANSFER => true,

    CURLOPT_ENCODING => '',

    CURLOPT_MAXREDIRS => 10,

    CURLOPT_TIMEOUT => 30,

    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,

    CURLOPT_CUSTOMREQUEST => 'POST',

    CURLOPT_HTTPHEADER => array(

        'cache-control: no-cache',

        'content-type: application/x-www-form-urlencoded'

    ),

));

$response = curl_exec($curl);

$err = curl_error($curl);

curl_close($curl);


// Decode JSON response and get only the data needed:

$response = json_decode($response);

$response = $response->disturbance[0];

var_dump($response);


$name = $response->title;

echo $name;

当我删除干扰背后的[0]时,我得到一个空白$name。有谁知道我该如何解决这个问题?


谢谢


函数式编程
浏览 75回答 1
1回答

忽然笑

您可以通过键访问对象,但“干扰”不是键,而是键可以取的值。type首先需要筛选数据以仅获取 包含 的项目,然后才能获取标题。type = 'disturbance'下面是一个示例:$response = json_decode($response); $disturbanceItems = array_filter($response, function ($item){return $item->type == 'disturbance';}); echo $disturbanceItems[0]->title ;
打开App,查看更多内容
随时随地看视频慕课网APP