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

Undefined offset when inserting data with Guzzle Laravel

我正在使用 Guzzle 从第三方 api 向我的数据库插入数据。一切似乎都很好,直到 api 中不存在这些字段之一。它带有错误:"UNDEFINED OFFSET",所以我认为这就是问题所在。 这是我的命令时间表:

        $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 带有不存在的字段,那么避免 "UNDEFINED OFFSET" 错误的最佳方法是什么?提前致谢。

您使用 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,

与...相同

bcdiv($item['odds'][0]['regular'][0]['odds'][0]['decimalValue'],1,2) ?? null

...

isset($item['odds'][0]['regular'][0]['odds'][0]['decimalValue']) ?
       bcdiv($item['odds'][0]['regular'][0]['odds'][0]['decimalValue'],1,2) 
      : null

对于您要插入的每个字段,添加一个检查是否已设置。

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