ErrorException 未定义偏移量:Laravel API 中的 0

问题描述

在我的 Laravel-8 应用程序中,我将这个 api 作为 json:

api/tracking/{TrackerID}?sub-key=jkkmkf

看起来像:

api/tracking/19SB22?sub-key=jkkmkf

这是一个GET请求

当我尝试如下所示使用它时,出现此错误

错误异常 未定义的偏移量:0

它指向这一行:

$current = $json[0];

我该如何解决这个问题?

谢谢

public function index() {
    $request = Request::create('/api/tracking','GET');
    $response = Route::dispatch($request);
    $information = $response->content();
    $json = json_decode($information,true);
    $current = $json[0];
    $geo = explode(',',$json[0]['current_asset_position_coord']);
    return view('welcome',[
        'current' => $current,'json' => $json,'geo' => $geo
    ]);
}

解决方法

这意味着数组 ($json) 不包含键为 0 的值,您的 json_decode 返回一个空数组。

要向外部 API 发出请求,请查看 Guzzle

use GuzzleHttp\Client;


$client = new Client();
$res = $client->get('https://example.com/api/tracking/19SB22',['sub-key' => 'jkkmkf']);
echo $res->getStatusCode(); // 200
$json = $res->getBody()->getContents();