简体   繁体   English

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

[英]ErrorException Undefined offset: 0 in Laravel API

In my Laravel-8 application, I have this api as json:在我的 Laravel-8 应用程序中,我有这个 api 作为 json:

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

which looks like:看起来像:

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

It is a GET request这是一个 GET 请求

When I tried to consume it as shown below, I got this error:当我尝试如下所示使用它时,出现此错误:

ErrorException Undefined offset: 0 ErrorException 未定义的偏移量:0

and it points to this line:它指向这一行:

$current = $json[0]; $当前 = $json[0];

How do I resolve this?我该如何解决这个问题?

Thanks谢谢

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
    ]);
}

It means that the array ( $json ) doensn't contains value with 0 key, your json_decode returns you an empty array.这意味着数组( $json )不包含 0 键的值,您的json_decode返回一个空数组。

To make requests to external API's please have a look at Guzzle要向外部 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM