在Laravel中检索json数据时遇到问题

时间:2019-07-29 11:18:52

标签: php laravel-5

我正在做一个laravel项目,并且遇到JSON错误。我尝试了几种解决方案,但没有提出任何解决方案。

在这个项目中,我必须根据一个“ ID”将多个数据发送到数据库中。在该ID中,需要插入10个数据。所以我使用JSON格式。这样可以节省很多,但是在尝试提取数据时会出错。

这是我的代码

控制器:

public function newExpenses(Request $request){

        $Jexpenses = new Jexpenses;

        $json = array(
            'des' => $request->description,
            'valu' => $request->expenses
        );

        $Jexpenses->voucher = $request->voucher_no;
        $Jexpenses->date = $request->date;
        $Jexpenses->description = json_encode($json);
        $Jexpenses->expenses = $request->total;
        $Jexpenses->remarks = $request->remark;

        if($Jexpenses->save()){
            $notification = array(
                'message' => 'Expenses Saved',
                'alert-type' => 'success'
            );
        }

        return redirect()->back()->with($notification);
    }

结果:

{"des":["Jon","Sam","Pitter"],"valu":["20","30","15"]}

返回控制器:

public function expenses(){
        $data = array(
            'title' => 'Expenses',
            'expenses' => Jexpenses::all()
        );

        return view('expenses.expenses')->with($data);
    }

html:

@foreach ($expenses as $key => $getData)


    {{ $array = @json( $getData->description ) }}


    <tr>
        <td>{{ ++$key }} </td>
        <td>{{ $getData->voucher }} </td>
        <td>{{ $getData->date }} </td>
        @foreach ($array->description as $k => $v)
           <td>{{ $array->des['$k'] }}</td>
            <td>{{ $array->valu['$k'] }}</td>
         @endforeach
        <td>{{ $getData->expenses }}</td>
        <td>{{ $getData->remarks }}</td>
    </tr>
 @endforeach

它应该可以正常工作,但会出现错误

错误:

syntax error, unexpected '<' (View: C:\xampp\htdocs\acSoft\resources\views\expenses\expenses.blade.php

需要一些帮助。谢谢。

1 个答案:

答案 0 :(得分:1)

1)使用as.data.frame()代替json_decode($getData->description)@json的简称为@json

2)json_encode不存在。应该是$array->description

3)您在$array->des引号中使用变量。您应该使用'引号或不使用舍入变量。

4)使用保留字作为变量名是一个坏主意。我是关于变量"

$array