使用Guzzle Laravel插入数据时未定义的偏移量

问题描述 投票:0回答:1

我通过使用Guzzle将数据从第三方api插入我的数据库。一切似乎都很好,直到api中不存在该字段之一。它带有错误:“未定义的偏移量”,因此认为这是问题所在。这是我的命令时间表:

        $client = new Client(['headers' => ['Accept' => 'application/json']]); 
        $res = $client->request('GET', 'https://example.com/api/apiKey=XXXXXXXXXXXXXXXXXXX');
        $data = json_decode($res->getBody()->getContents(),true);
        $events = $data['Data'];

        foreach($events as $item)
        {
                        DB::table('apidata')->updateOrInsert([
                'matchID'=>$item['matchID']],
                [
                'matchID'=>$item['matchID'] ?? null,
                'startTime'=>date('Y-m-d H:i', strtotime($item['startTime'])) ?? null,
                'timeLive'=>$item['timeLive'] ?? null,
                'homeTeam'=>$item['homeTeamInfo']['homeTeam'] ?? null,
                'homeGoals' =>$item['homeTeamInfo']['homeGoals'] ?? null,
                'awayGoals'=>$item['awayTeamInfo']['awayGoals'] ?? null,
                'awayTeam'=>$item['awayTeamInfo']['awayTeam'] ?? null,

因此,如果api带有不存在的字段,那么避免“未定义的偏移”错误的最佳方法是什么?预先感谢。

php laravel guzzle
1个回答
0
投票

您使用startTime元素的方式无法满足找不到该值的问题。 ?? null位仅在尝试将其转换为时间然后转换为日期后才使用...

'startTime'=>date('Y-m-d H:i', strtotime($item['startTime'])) ?? null,

在这种情况下,使用isset() ...的旧方法可能会更好。

'startTime'=>isset($item['startTime']) ?date('Y-m-d H:i', strtotime($item['startTime'])) 
                                        : null,
© www.soinside.com 2019 - 2024. All rights reserved.