dtl4521 2017-08-07 15:02
浏览 39
已采纳

Laravel刀片迭代php数组/对象

I'm having trouble outputting a list of key value pairs in Laravel blade.

My show.blade.php template is:

@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:

  • incrementing
  • exists
  • wasRecentlyCreated
  • 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}

Ideally, I would like to see a list of bullet points showing e.g.:

  • date: 8/07/2017
  • time: 12:00:01
  • boat_name: cyclone
  • 写回答

2条回答 默认 最新

  • doujie9882 2017-08-07 15:07
    关注

    The function Hyfes::find(1) will return an object of the type App\Hyfes and not an array. 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.

    A better way to do this is using the Laravel getAttributes function. This will only get the attributes loaded from the database. Like so:

    @foreach ($datapoint->getAttributes() as $key => $value)
        <li>{{ $key }}: {{ $value }}</li>
    @endforeach
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据