我将这个嵌套数组放在变量$ audits下,并将其移交给Laravel 5.8视图:
array:4 [▼
0 => array:3 [▼
"action" => "Case initiated by:"
"user" => "Doe, Jane"
"timestamp" => Carbon @1558353758 {#419 ▶}
]
1 => array:3 [▼
"action" => "New head mediator:"
"user" => "Doe, Jane"
"timestamp" => Carbon @1558353758 {#430 ▶}
]
2 => array:3 [▼
"action" => "Case closed by:"
"user" => "Doe, Jane"
"timestamp" => Carbon @1558353787 {#467 ▶}
]
3 => array:3 [▼
"action" => "Case re-opened by:"
"user" => "Doe, Jane"
"timestamp" => Carbon @1558353791 {#474 ▶}
]
]
我的目标是在视图中填充表格以获取以下输出:
Action User Date/time (UTC)
-------------------------------------------------------
Case initiated by: Doe, Jane 2019-05-20 12:02:38
New head mediator: Doe, Jane 2019-05-20 12:02:38
Case closed by: Doe, Jane 2019-05-20 12:03:07
Case re-opened by: Doe, Jane 2019-05-20 12:03:11
为此,我希望能够像这样循环遍历:
<table>
<th>Action</th>
<th>User</th>
<th>Date/time (UTC)</th>
@foreach ($audits as $audit)
@foreach ($audit as $value)
<tr>
<td>{{ $value['action'] }}</td>
<td>{{ $value['user'] }}</td>
<td>{{ $value['timestamp'] }}</td>
</tr>
@endforeach
@endforeach
</table>
但是,这将给我错误消息,因为该视图似乎仅能处理字符串,因此似乎无法从数组中检索此类特定值。 因此,我尝试将数组转换为对象,使用JSON编码等,但无济于事。
在控制器中构造数组的方式是这样的(也许有人可以向我指出如何制作适当的集合或对象,以便可以由视图更好地处理它的方向):
public function show(Project $project)
{
$audits_raw= $project->audits;
foreach ($audits_raw as $audit_raw) {
foreach ($audit_raw->new_values as $action => $id) {
if ($action == 'initiator_id') {
$actions[] = 'Case initiated by:';
$users[] = $this->userName($id);
$timestamps[] = $audit_raw->updated_at;
} elseif ($action == 'head_mediator_id') {
$actions[] = 'New head mediator:';
$users[] = $this->userName($id);
$timestamps[] = $audit_raw->updated_at;
} elseif ($action == 'marked_for_deletion' && $id == 1) {
$actions[] = 'Case closed by:';
$users[] = $this->userName($audit_raw->user_id);
$timestamps[] = $audit_raw->updated_at;
} elseif ($action == 'marked_for_deletion' && $id == 0) {
$actions[] = 'Case re-opened by:';
$users[] = $this->userName($audit_raw->user_id);
$timestamps[] = $audit_raw->updated_at;
}
}
}
$audits = array_map(function ($action, $user, $timestamp) {
return array_combine(
['action', 'user', 'timestamp'],
[$action, $user, $timestamp]
);
}, $actions, $users, $timestamps);
return view('admin.billing.show', compact('project', 'audits', 'actions'));
}
protected function userName($id)
{
$user = User::where('id', $id)->first();
$username = $user->last_name.', '.$user->first_name;
return $username;
}
非常感谢!
答案 0 :(得分:0)
您可以将嵌套数组保留在变量$audits
下,并使用Carbon将date object
转换为string
:
@foreach ($audits as $audit)
<tr>
@foreach ($audit as $value)
<td>{{ $value['action'] }}</td>
<td>{{ $value['user'] }}</td>
<td>{{ Carbon\Carbon::parse($value['timestamp'])->format('Y-m-d H:i:s') }}</td>
@endforeach
</tr>
@endforeach
答案 1 :(得分:0)
更改视图。
@foreach($audits as $key)
<tr>
<td>{{ $key['action'] }}</td>
<td>{{ $key['user'] }}</td>
<td>{{ Carbon\Carbon::parse($key['timestamp'])->format('Y-m-d H:i:s') }} .
</td>
</tr>
@endforeach