Php Laravel 5.4集合-如何通过索引从集合中获取数据

Php Laravel 5.4集合-如何通过索引从集合中获取数据,php,mysql,laravel,Php,Mysql,Laravel,您可以阅读最后一行,因为第一部分的内容只是对我的情况的解释。:) 我在前面看到了一个语法,我可以从集合中获取数据,该集合使用索引压缩到视图文件中 因此,对于我的情况,我想在刀片内部使用键循环,作为使用此语法的索引值 foreach ($variable as $key => $value) { } 现在我收藏了4本参考代码,库存,成本,价格 这是我如何得到它们的问题。(它的设计很差,请建议是否有更好的查询来获取所有内容的唯一性。) //每个项目的参考代码 $ref_code

您可以阅读最后一行,因为第一部分的内容只是对我的情况的解释。:)

我在前面看到了一个
语法
,我可以从
集合
中获取数据,该集合使用
索引
压缩到
视图
文件中

因此,对于我的情况,我想在刀片内部使用
循环,作为使用此语法的索引值

foreach ($variable as $key => $value)
   {

   }
现在我收藏了4本<代码>参考代码,
库存
成本
价格

这是我如何得到它们的问题。(它的设计很差,请建议是否有更好的查询来获取所有内容的唯一性。)

//每个项目的参考代码
$ref_code=InventoryLogs::whereDate('created_at','>=',$request->datefrom)
->whereDate('created_at','=',$request->datefrom)
->whereDate('created_at','=',$request->datefrom)
->whereDate('created_at','=',$request->datefrom)
->whereDate('created_at','p>将
->toArray()
附加在以下代码行中

$ref_codes = InventoryLogs::whereDate('created_at','>=', $request->datefrom)
        ->whereDate('created_at', '<=', $request->dateto)
        ->orderBy('ref_code', 'asc')
        ->groupBy('ref_code')
        ->get()->toArray();

    $stocks = InventoryLogs::whereIn('id',$stock_ids)->get()->toArray();

    $costs = InventoryLogs::whereIn('id',$cost_ids)->get()->toArray();

    $prices = InventoryLogs::whereIn('id',$price_ids)->get()->toArray();
$ref\u code=InventoryLogs::whereDate('created\u at','>=',$request->datefrom)

->whereDate('created_at',”您需要在代码中进行以下更改:

get()之后添加keyBy()

在循环中,将索引更改为$ref\u code->ref\u code

$stocks[{$ref_code->ref_code}]

如果您想循环,您不使用forelse吗?最好使用foreach,您将获得如下索引

@foreach($ref_codes as $ref_code) 
<tr>
 <td>{{ $ref_code->ref_code}}</td>
 <td>{{ $ref_code->stocks }}</td> 
<td>{{ $ref_code->costs }}</td> 
<td>{{ $ref_code->prices }}</td> 
</tr>
 @endforeach
@foreach($ref\u代码为$ref\u代码)
{{$ref\u code->ref\u code}
{{$ref_code->stocks}
{{$ref_code->costs}
{{$ref_code->prices}
@endforeach

只需使用
toArray()将集合更改为数组即可
这样你就可以使用键值对了。你的答案再次证明了这一点,哈哈。但这并没有解决我的问题,但正因为如此,我知道我的查询结构非常糟糕,很容易出错。:p你需要优化方法。编写一个复杂的查询来实现你想要的。一般循环的执行速度比复杂循环慢查询执行
<table id = "myTable" class="table table-hover">
    <thead>
    <tr>
        <th>Reference Code</th>
        <th>Quantity</th>
        <th>Cost</th>
        <th>Price</th>
    </tr>
    </thead>
    <tbody>
    @forelse($ref_codes as $key => $ref_code)
    <tr>
        <td>{{$ref_code['ref_code']}}</td>
        <td>{{$stocks[$key]['column_name']}}</td>
        <td>{{$costs[$key]['column_name']}}</td>
        <td>{{$prices[$key]['column_name']}}</td>
    </tr>
    @empty
    @endforelse
    </tbody>
</table>
InventoryLogs::whereIn('id',$cost_ids)->get()->keyBy('ref_code');
$stocks[{$ref_code->ref_code}]
@foreach($ref_codes as $ref_code) 
<tr>
 <td>{{ $ref_code->ref_code}}</td>
 <td>{{ $ref_code->stocks }}</td> 
<td>{{ $ref_code->costs }}</td> 
<td>{{ $ref_code->prices }}</td> 
</tr>
 @endforeach