【问题标题】:ErrorException Undefined offset: 0 in Laravel APIErrorException 未定义的偏移量:Laravel API 中的 0
【发布时间】:2021-05-31 01:08:34
【问题描述】:

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

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

看起来像:

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

这是一个 GET 请求

当我尝试使用它时,如下所示,我收到了这个错误:

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

它指向这一行:

$当前 = $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
    ]);
}

【问题讨论】:

    标签: laravel api


    【解决方案1】:

    这意味着数组 ($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();
    

    【讨论】:

    • 如何在 $request = Request::create('/api/跟踪', 'GET');
    猜你喜欢
    • 2021-07-06
    • 1970-01-01
    • 2021-01-25
    • 2019-03-21
    • 1970-01-01
    • 1970-01-01
    • 2014-06-25
    • 2020-01-02
    • 1970-01-01
    相关资源
    最近更新 更多