laravel 如何在 Blade 视图中显示 JSON 数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41523475/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:05:09  来源:igfitidea点击:

How to display JSON Array in Blade view?

jsonlaravellaravel-5

提问by rmdy

My db table structure

我的数据库表结构

I'm using a view composer to get data from this table and send it back to my view

我正在使用视图编辑器从该表中获取数据并将其发送回我的视图

class NavComposer
{

 public function compose(View $view)
    {
        if (Auth::check()) {
            $view->with('unread_notifications', DB::table('notifications')->where([
                                            ['read_at', '=', NULL],
                                            ['notifiable_id', '=', Auth::user()->id],
                                            ])->get());
        }
    }
}

My view:

我的看法:

@foreach($unread_notifications as $notification)
{{ $notification->data }}
@endforeach

What I am getting:

我得到了什么:

{"id":79,"sender":"Diana","receiver":"Alex","subject":"Subject","body":"Lorem ipsum"}

What I want to display:

我想显示的内容:

ID: 79
Subject: Subject
Body: Lorem Ipsum

I apologize in advance if this is very simple stuff I dont know much about JSON

如果这是非常简单的东西,我提前道歉,我对 JSON 不太了解

采纳答案by Alexey Mezenin

You need to decode JSON. You can do this manually:

您需要解码 JSON。您可以手动执行此操作:

@foreach($unread_notifications as $notification)
    <?php $notificationData = json_decode($notification->data, true); ?>
    {{ $notificationData['sender'] }}
@endforeach

Or you can create accessorso Laravel could automatically convert JSON to an array:

或者您可以创建访问器,以便 Laravel 可以自动将 JSON 转换为数组:

public function getDataAttribute($value)
{
    return json_decode($value, true);
}

回答by Raymond Cheng

@foreach($unread_notifications as $notification)
   @foreach(json_decode($notification->data, true) as $d)
      <div>ID: {{ $d['id'] }}</div>
      <div>Subject: {{ $d['subject'] }}</div>
      <div>Body: {{ $d['body'] }}</div>
   @endforeach
@endforeach