我最近在尝试使用Laravel 4,到目前为止非常喜欢。然而,我遇到了一个问题,不是Laravel 4的问题,而是我的能力问题。
我有一个包含3行4列的数据库。例如,假设这些列是:
content_id, content_type, content_data, timestamp
'content_data'列包含一个大约有4个键值对的JSON编码数组。
当我从数据库中检索这些行(使用Eloquent)并将数据传递到我的视图时,如何解析JSON并在我的Blade模板中使用它?
在搜索和参考Laravel文档后,我的想法是您不能这样做,因此我尝试在控制器中将JSON解码回数组,然后将其传递到视图中。
到目前为止,在我的类中,我尝试了以下内容:
<?php
class PageController extends \BaseController {
public function index()
{
$data = Content::
->where('content_type', 1)
->get();
foreach($data as $content)
{
$items[] = json_decode($content->content_data);
}
return View::make('pages.page2')
->with('data', $data)
->with('items', $items);
}
}
然而在我的 Blade 模板中,当我运行 foreach 循环来遍历提取的行时,我尝试在第一个循环内运行另一个 foreach 循环,以遍历 $items 数组以提取它们的值,但由于这是一个嵌套循环,我得到了重复的 JSON 值。
我的 Blade 模板如下:
@extends('layouts.pages');
@section('content_body')
<h1>My <span>title</span></h1>
<div class="column col-1">
<ul>
{{-- loop through the database rows --}}
@foreach($data as $row)
{{-- loop through the json decoded values --}}
@foreach($items as $item)
{{ $item['title'] }}
@endforeach
@endforeach
</ul>
</div>
@stop
我不确定我是否解释得正确,但基本上我只想在显示提取的数据库行的循环中解析我的json编码数组。
希望能有人能够理解并提供帮助。
$content->content_data = json_decode($content->content_data)
。 - elclanrs