【问题标题】:Laravel blade iterating over php array/objectLaravel 刀片遍历 php 数组/对象
【发布时间】:2017-08-07 15:02:21
【问题描述】:

我无法在 Laravel Blade 中输出键值对列表。

我的 show.blade.php 模板是:

@extends('layouts.app')

@section('content')

  <ul>
    @foreach ($datapoint as $key => $value)

      <li>{{ $key, $value }}</li>

    @endforeach
  </ul>

  {{ $datapoint }}
@endsection

显示此模板的控制器是:

<?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);
    }
}

在浏览器中输出到视图的数据是这样的:

  • 递增
  • 存在
  • 是最近创建的
  • 时间戳

    {"date":"08/07/2017","time":"12:02:25","boat_name":"cyclone","current_location":"North Greenwich Pier","status": “停靠”,“登船”:26,“下船”: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}

理想情况下,我希望看到一个项目符号列表,例如:

  • 日期:2017 年 8 月 7 日
  • 时间:12:00:01
  • 船名:旋风

【问题讨论】:

  • 可能是因为 find 没有返回数组?

标签: php laravel laravel-5.4 blade


【解决方案1】:

函数Hyfes::find(1) 将返回App\Hyfes 类型的对象,而不是数组。通过遍历键值对,您将获得所有属性。 Laravel 添加了许多额外的属性来跟踪对象。

一个更好的方法是使用 Laravel getAttributes 函数。这只会获取从数据库加载的属性。 像这样:

@foreach ($datapoint->getAttributes() as $key => $value)
    <li>{{ $key }}: {{ $value }}</li>
@endforeach

【讨论】:

  • 很高兴我能帮上忙。 :) 考虑将此标记为您问题的答案,以便其他用户也可以找到它。
【解决方案2】:

您正在尝试迭代模板中的非数组变量。您必须明确说明您希望在模板中看到的对象的值。

@extends('layouts.app')

@section('content')

  <ul>
      <li>date: {{ $datapoint->date }}</li>
      <li>time: {{ $datapoint->time }}</li>
      <!-- and so on -->
  </ul>

@endsection

【讨论】:

    猜你喜欢
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 2019-09-16
    • 2014-06-18
    • 2017-09-19
    相关资源
    最近更新 更多