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条)

报告相同问题?

悬赏问题

  • ¥20 蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏