我正在尝试从RestFul api获取数据收集,当$ response变量返回数据时,一切都很好,但是如果没有,我就遇到了问题,这是我的代码:
public function showAsStage($id)
{
try {
$notis = Notification::with('stage')->orderBy('created_at', 'desc')
->where('stage_id', $id)
->get();
if(!$notis->isEmpty()){
foreach($notis as $noti){
$json = $noti->file ? json_decode($noti->file) : '';
$file = $json ? (string)$json[0]->download_link : '';
$response[] = [
'id' => $noti->id ? $noti->id : '',
'body' => $noti->body ? $noti->body : '',
'stage' => $noti->stage->stage ? $noti->stage->stage : '',
'time' => $noti->created_at ? $noti->created_at : '',
'course' => "عام",
'image' => $noti->file ?'http://172.18.23.41:8000/storage/'.$file : null
];
}
}
}catch(\Exception $e){
return $this->sendError('Server Error.', $e->getMessage());
}finally{
return $this->sendResponse($response, 'Successfully fetch noti meta data');
}
}
没有数据时:
"Undefined variable: response"
答案 0 :(得分:1)
发生这种情况是因为您尚未在foreach循环($reponse=[]
)之前分配变量。因此,为了解决此问题,请在try
范围之前和内部创建一个空数组使用array_push()