在Blade中显示JSON集合

时间:2019-02-05 07:04:38

标签: json laravel laravel-blade

我正在尝试使用Laravel和Blade显示我数据库中的JSON数据。

我的JSON数据如下:

[
    {
        "title": "Open Projects",
        "sequence": "1",
        "columns": [
            "Open Projects",
            "Owner"
        ],
        "col": {
            "index": "1",
            "value": "title",
            "type": "longtext",
            "heading": "1"
        },
        "0": {
            "title": "Owner",
            "index": "2",
            "value": "owner",
            "type": "longtext",
            "heading": "0"
        }
    },
    ... more
]

当我尝试打印其中一个馆藏时,出现错误: "htmlspecialchars() expects parameter 1 to be string, array given (View: ...)"

1 个答案:

答案 0 :(得分:0)

当您尝试使用"htmlspecialchars() expects parameter 1 to be string, array given打印阵列时,会发生

{{ $variable }}。相反,您将需要将其转换为字符串或在其上循环。下面的解决方案遍历您的收藏集。

假设您像这样注入JSON:

return view('myview', ["json" => json_decode($json, true)]);

您可以像这样打印您的值:

@foreach($json as $project)
    <p>Title: {{ $project["title"] }}</p>
    <p>Sequence: {{ $project["sequence"] }}</p>
    <p>Columns: </p>
    <ul>
        @foreach($project["col"] as $key => $value)
            <li>{{ $key }} : {{ $value }}</li>
        @endforeach
    </ul>
    <p>"0" <- whatever this is</p>
    <ul>
        @foreach($project["0"] as $key => $value)
            <li>{{ $key }} : {{ $value }}</li>
        @endforeach
    </ul>
@endforeach