Laravel 5.0无法解析数组来查看

时间:2016-04-29 09:52:34

标签: php arrays laravel laravel-5 controller

无法解析数组以进行查看。

这是数组

 Array (
    [positions] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [company_id] => 1
                    [title] => Software Developer
                )

            [1] => Array
                (
                    [id] => 2
                    [company_id] => 2
                    [title] => Accountant
                )

            [2] => Array
                (
                    [id] => 3
                    [company_id] => 3
                    [title] => Insurance salesman
                )
        )
)

这是控制器

$data = array(
    'positions' => $newarray['data']
);
return view('mypage', $data);

这是我试图回应标题的视图

@foreach($positions as $position)
{{ $position->title }}<br>
@endforeach

我在视图“试图获取非对象的属性”

中收到此错误

3 个答案:

答案 0 :(得分:2)

@foreach($positions as $position)
  {{ $position['title'] }}<br>
@endforeach

答案 1 :(得分:0)

我已经回答了类似的问题here,但是如果它有帮助的话,就在这里。

@foreach($data['positions'] as $position)
{{ $position['title'] }}<br>
@endforeach

另外,你应该改变:

$data = array(
    'positions' => $newarray['data']
);

类似于:

$data = array(
    'positions' => $someDataArray;
);

答案 2 :(得分:0)

首先正确格式化数组,如下所示:

$positions = array
(
    array(
        'id' => 1,
        'company_id' => 1,
        'title' => 'Software Developer'
    ),
    array(
        'id' => 2,
        'company_id' => 2,
        'title' => 'Accountant'
    ),
    array(
        'id' => 3,
        'company_id' => 3,
        'title' => 'Insurance salesman'
    )
);

将数据传递给视图:

$data = array(
    'positions' => $positions
);
return view('mypage', $data);

现在您可以回复标题如下:

@foreach($positions as $position)
    {{ $position['title'] }}<br>
@endforeach