从 Laravel 中的 View 格式化 JSON 数据
Posted
技术标签:
【中文标题】从 Laravel 中的 View 格式化 JSON 数据【英文标题】:Formatting JSON data from View in Laravel 【发布时间】:2015-07-25 19:36:09 【问题描述】:我正在尝试以这种类型的插图格式在我的视图中显示我的数据。方括号内的项目是表格的标题。
[Lecture]
ECE 201 Section 1 .. ..
ECE 201 Section 2 .. ..
ECE 201 Section 3 .. ..
[Lab]
ECE 201 Section 10 .. ..
ECE 201 Section 11 .. ..
ECE 201 Section 12 .. ..
[Recitation]
ECE 201 Section 20 .. ..
ECE 201 Section 21 .. ..
ECE 201 Section 22 .. ..
我的 JSON,好吧,对于一个类,如下所示
year: "2015",
term: "Summer",
subject_code: "ECE",
course_no: "201",
instr_type: "Lecture",
instr_method: "Face To Face",
section: "003",
crn: "42953",
course_title: "Digital Logic",
credits: "3.0",
day: "R",
time: "06:30 pm - 09:20 pm",
instructor: "Teacher Name",
campus: "University Building",
max_enroll: "18",
enroll: "18",
building: "PLACE",
room: null,
description: "Introduction to logic for computing",
pre_reqs: "",
co_reqs: ""
本质上,我想将instr_type
ONCE 显示为表的表头,并在表中显示相应的数据。您可以假设数据返回按instr_type
排序,因此如果您有多个实验室和讲座,它将像这样返回 - 实验室、实验室、实验室、讲座、讲座等
如果我的数据采用这种格式,我觉得我想做的事情会更容易实现:
year: "2015",
term: "Summer",
subject_code: "ECE",
course_no: "201",
instr_type: "Lecture",
info: [
instr_method: "Face To Face",
section: "003",
crn: "42953",
course_title: "Digital Logic",
credits: "3.0",
day: "R",
time: "06:30 pm - 09:20 pm",
instructor: "Teacher Name",
campus: "University Building",
max_enroll: "18",
enroll: "18",
building: "PLACE",
room: null,
description: "Introduction to logic for computing",
pre_reqs: "",
co_reqs: ""
,
instr_method: "Face To Face",
section: "004",
crn: "42954",
..
]
我的问题是如何在我的控制器或视图中格式化我的数据,以便实现这种效果?为这个愚蠢的问题道歉;我觉得这个问题的答案很简单,只是我想多了。
【问题讨论】:
【参考方案1】:我发现使用两个循环最适合这种事情。
// in your Controller
$classesByType = [];
foreach ($classes => $class)
$classesByType[$class['instr_type']][] = $class;
return view('my-view', ['classesByType' => $classesByType]);
// In your Blade template
@foreach ($classesByType as $type => $classes)
<h1> $type </h1>
@foreach ($classes as $class)
<p> $class['subject_code'] $class['course_code'] ...</p>
@endforeach
@endforeach
如果您想按其他元素进行分类,只需添加另一个循环/数组级别:
// in your Controller
$classesByLabelAndType = [];
foreach ($classes => $class)
$label = $class['subject_code'] . " " . $class['course_no'];
$classesByLabelAndType[$label][$class['instr_type']][] = $class;
return view('my-view', ['classesByLabelAndType' => $classesByLabelAndType]);
// In your Blade template
@foreach ($classesByLabelAndType as $label => $classesByType)
<h1> $label </h1>
@foreach ($classesByType as $type => $classes)
<h2> $type </h2>
@foreach ($classes as $class)
<p> $class['course_code'] ...</p>
@endforeach
@endforeach
@endforeach
【讨论】:
正是我想要的。谢谢=)。 很高兴为您提供帮助!并非我们所有人都有超过一千个声誉,所以绿色复选标记将不胜感激! :) 我会在两分钟内接受! *** 限制 =) 啊,没有意识到——我是新手。谢谢! 嘿@Ben。我将如何计算$classesByType
数组的总类数?我试过count($classesByType)
,但显然,它只返回instr_type
的数量以上是关于从 Laravel 中的 View 格式化 JSON 数据的主要内容,如果未能解决你的问题,请参考以下文章