【问题标题】:how to foreach the json array in laravel php?如何在 laravel php 中获取 json 数组?
【发布时间】:2021-05-12 01:27:49
【问题描述】:

这是我的数组[{"total":"03:00:00"},{"total":"08:00:00"},{"total":"04:00:00"}],它是查询的结果:

$total_hrs = UserDetails::where('userId','=', $id->selectRaw('time((TIMEDIFF( logged_out_time, logged_in_time ))) as total')->get();

我的看法:

<tr>
  @for ($i = 1; $i < 8; $i++)
    <td style="height:50px;"> {{$i}}<br>
    @foreach ($dt as $key => $dz)
      @if(Carbon\Carbon::parse($dz)->day == $i)
       
        @foreach ($total_hrs as $h)
          {{$h["total"]}}
        @endforeach
     
      @endif
    @endforeach
    </td>
  @endfor
</tr>

在我看来,整个数据结果即将到来。我只想要一个迄今为止的数据。

期望的输出: enter image description here

【问题讨论】:

  • 您对此有何疑问?
  • 你缺少 json_decode 吗?试试@foreach (json_decode($total_hrs) as $h)
  • @Marko 是的,我在控制器中使用过 json 解码。但仍然无法一一获取值。
  • @NicoHaase 实际上我想要数组 [total] 中的一个一个值,但我得到一个 'dt' 的所有三个值。'[dt] 是日期数组。所以对于一个特定日期 - >一个总小时值。
  • 我不确定您要做什么,但是您的 $total_hrs foreach 循环将始终输出所有 3 个值,因为循环内没有条件。您是否缺少 IF 语句?编辑您的问题并提供所需的输出

标签: php arrays json laravel foreach


【解决方案1】:
$weekMap = [
    0 => 'MO',
    1 => 'TU',
    2 => 'WE',
    3 => 'TH',
    4 => 'FR',
    5 => 'SA',
    6 => 'SU',
];
<tr>
    @for ($i = 0; $i < 7; $i++)
         <th>$weekMap[$i]</th>
    @endfor
</tr>
<tr>
    <td style="height:50px;"> 
        <div>{{$i}}</div>
        @foreach ($dt as $key => $dz)  
           @if(Carbon\Carbon::parse($dz)->day == $i)
             <div> 
             @foreach ($total_hrs as $h)
                 <span>{{$h->total}}</span>    // this will print 03:00:00 08:00:00 04:00:00
             @endforeach
             </div>
           @endif
        @endforeach
    </td>
</tr>

【讨论】:

  • 谢谢。但是我想要 03:00:00 日期为 2 月 3 日,08:00:00 为 2 月 4 日,特别是这样。
  • 在这种情况下,您必须根据数据库中的日期存储时间日志。如果您已经这样做了,那么还可以使用时间日志获取日期。现在您只需比较日期并在该日期打印相应的时间日志。 :D
  • 感谢您对答案的投票。 :)
猜你喜欢
  • 2016-11-22
  • 1970-01-01
  • 2019-05-13
  • 1970-01-01
  • 2019-07-05
  • 2021-03-05
  • 2017-03-15
  • 1970-01-01
  • 2016-06-06
相关资源
最近更新 更多