[英]Laravel blade iterating over php array/object
I'm having trouble outputting a list of key value pairs in Laravel blade. 我在Laravel Blade中输出键值对列表时遇到问题。
My show.blade.php template is: 我的show.blade.php模板是:
@extends('layouts.app')
@section('content')
<ul>
@foreach ($datapoint as $key => $value)
<li>{{ $key, $value }}</li>
@endforeach
</ul>
{{ $datapoint }}
@endsection
And my controller which displays this template is: 显示此模板的控制器是:
<?php
namespace App\Http\Controllers;
use App\Hyfes;
use Illuminate\Http\Request;
class CaptainController extends Controller
{
public function getLiveData ()
{
$datapoint = Hyfes::find(1);
return view('captain.show')->with('datapoint', $datapoint);
}
}
The data output to the view in the browser is this: 在浏览器中输出到视图的数据是这样的:
timestamps 时间戳记
{"date":"08/07/2017","time":"12:02:25","boat_name":"cyclone","current_location":"North Greenwich Pier","status":"docked","embarked":26,"disembarked":2,"people_on_board":24,"current_speed":0,"hotel_power":231,"battery_power_demand":342,"battery_output_power":23,"engine_output_power":12,"battery_power_stored":100,"battery_depth_of_discharge":323,"fuel_consumption_rate":7,"nox":432,"co2":213,"battery_state_of_charge":100,"id":1} {“ date”:“ 08/07/2017”,“ time”:“ 12:02:25”,“ boat_name”:“ Cyclone”,“ current_location”:“ North Greenwich Pier”,“ status”:“ docked” ,“进站”:26,“进站”:2,“船上人员”:24,“当前速度”:0,“酒店功率”:231,“电池功率需求”:342,“电池输出功率”:23,“发动机输出功率”:12,“ battery_power_stored“:100,” battery_of_discharge“:323,” fuel_consumption_rate“:7,” nox“:432,” co2“:213,” battery_state_of_charge“:100,” id“:1}
Ideally, I would like to see a list of bullet points showing eg: 理想情况下,我希望看到显示以下项目符号的列表:
The function Hyfes::find(1)
will return an object of the type App\\Hyfes
and not an array. 函数
Hyfes::find(1)
将返回App\\Hyfes
类型的对象,而不是数组。 By looping over the key value pairs you are getting all properties. 通过遍历键值对,您可以获得所有属性。 Laravel adds a lot of extra properties for keeping track of the object.
Laravel增加了许多额外的属性来跟踪对象。
A better way to do this is using the Laravel getAttributes
function. 更好的方法是使用Laravel
getAttributes
函数。 This will only get the attributes loaded from the database. 这只会获取从数据库加载的属性。 Like so:
像这样:
@foreach ($datapoint->getAttributes() as $key => $value)
<li>{{ $key }}: {{ $value }}</li>
@endforeach
You are trying to iterate over a non array variable in your template. 您正在尝试遍历模板中的非数组变量。 You have to be explicit about the values of the objects you would like to see in your template.
您必须明确要在模板中看到的对象的值。
@extends('layouts.app')
@section('content')
<ul>
<li>date: {{ $datapoint->date }}</li>
<li>time: {{ $datapoint->time }}</li>
<!-- and so on -->
</ul>
@endsection
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.