ErrorException未定义的偏移量:0

时间:2019-08-30 04:18:34

标签: php laravel

我是Laravel框架的新手。我尝试在我的PC上运行我的朋友项目,并在打开某个菜单时出现错误,并且在浏览器中运行代码时,它显示ErrorException (E_NOTICE) Undefined offset: 0。我该怎么做才能解决此错误?

这是处理菜单的控制器

public function getViewPesananCust(){
        $userId = Auth::user()->id;
        $data['transaksi'] = Transaction::select('*', 'transaction.id as id_transaksi')
        ->join('users as pemesan', 'pemesan.id', 'transaction.id_user')
        ->where('transaction.id_user', '=', $userId)
        ->orderBy('timestamp', 'DESC')->get();
        $data['rating_user'] = array();
        $x = Transaction::where('id_user', $userId)->where('status_transaksi', 1)->orderBy('timestamp', 'DESC')->get();
        $a = array();
        foreach($x as $y) {
            $z = Transaksi::where('id_transaksi', $y['id_transaksi'])->get()[0];
            array_push($a, $z);
        }
        $b = array();
        foreach($a as $y) {
            $z = Menu::where('id',$y['id_menu'])->get()[0];
            array_push($b, $z);
        }
        $c = array();
        foreach($b as $y) {
            $z = Rating::where('id_menu', $y['id'])->get()[0];
            array_push($c, $z);
        }
        $data['rating_user'] = $c;

        return view('pesanan', $data);
    }

2 个答案:

答案 0 :(得分:0)

由于您的第一个循环在一个集合上,因此它的循环很好,但是对于第二个循环,您需要使用键值对,因为它在关联数组上循环。

       foreach($a as $key=>$value) {
          $z = Menu::where('id',$value['id_menu'])->get()[0];
          array_push($b, $z);
       }

答案 1 :(得分:0)

查询数据库可能返回空结果。使用前,您需要检查查询结果中存在的数据。

   public function getViewPesananCust(){
        $userId = Auth::user()->id;
        $data['transaksi'] = Transaction::select('*', 'transaction.id as id_transaksi')
        ->join('users as pemesan', 'pemesan.id', 'transaction.id_user')
        ->where('transaction.id_user', '=', $userId)
        ->orderBy('timestamp', 'DESC')->get();
        $data['rating_user'] = array();
        $x = Transaction::where('id_user', $userId)->where('status_transaksi', 1)->orderBy('timestamp', 'DESC')->get();
        $a = array();
        foreach($x as $y) {
            // check empty records
            $d1 = Transaksi::where('id_transaksi', $y['id_transaksi'])->get();
            if($d1 && count(d1) > 0){
                $z = $d1[0];
                array_push($a, $z);
            }
        }
        $b = array();
        foreach($a as $y) {
            $d2 = Menu::where('id',$y['id_menu'])->get();
            // check empty records
            if($d2 && count(d2) > 0){
                $z = $d2[0];
                array_push($b, $z);
            }
        }
        $c = array();
        foreach($b as $y) {                
            $d3 = Menu::where('id',$y['id_menu'])->get();
            // check empty records
            if($d3 && count(d3) > 0){
                $z = $d3[0];
                array_push($c, $z);
            }
        }
        $data['rating_user'] = $c;

        return view('pesanan', $data);
    }