我与我的应用混淆了,我在从Twitter API显示image_url数据时遇到了问题。
CONTROLLER
$events = Event::findOrFail($id);
$query = $events->hashtag;
// Application Programming Interface
$stack = HandlerStack::create();
$middleware = new Oauth1([
'consumer_key' => 'CONSUMER_KEY',
'consumer_secret' => 'CONSUMER_SECRET',
'token' => 'TOKEN',
'token_secret' => 'TOKEN_SECRET'
]);
$stack->push($middleware);
$client = new Client([
'base_uri' => 'https://api.twitter.com/1.1/',
'handler' => $stack,
'auth' => 'oauth'
]);
$res = $client->get('https://api.twitter.com/1.1/search/tweets.json?q=%23', [
'query' => ['q' => $query]
]);
$array = json_decode($res->getBody()->getContents(), true);
$tes = (count($array['statuses']));
if($request->user()->cannot('show', $events)){
abort(405);
}else{
return view('dashboard.events.show', compact('events'), [
'events' => $events
])->with([
'array'=> $array,
'tes' => $tes
]);
}
查看
@for ($i = 0; $i < $tes; $i++)
<div class="col-md-4">
<img src="{{$array['statuses'][$i]['entities']['media'][0]['media_url']}}" alt="" class="img-responsive"/>
</div>
@endfor
RESULT
Error Messages:
Undefined index: media
在twitter API v1.1上,当人们没有发布图片时媒体实体就消失了,所以当我试图用循环概念获取json数据时,media_url对象是未定义的,而且我的结果是错误消息。 对不起我的英语太糟糕了,我还是php和api的新手。
答案 0 :(得分:2)
您的代码很好,而且您说有时候没有['media']属性,所以您想使用这样的东西:
@for ($i = 0; $i < $tes; $i++)
@if(isset($array['statuses'][$i]['entities']['media']))
<div class="col-md-4">
<img src="{{$array['statuses'][$i]['entities']['media'][0]['media_url']}}" alt="" class="img-responsive"/>
</div>
@endif
@endfor
因此,当$array
中有图片时,您的视图会生成HTML以显示它。如果你没有,它将被跳过。