【发布时间】:2021-05-17 13:36:32
【问题描述】:
我有一个多维数组,我将它传递给 laravel 中的视图。该数组用于使用刀片语法将数据输出到视图。但是,当我尝试访问 @foreach 循环中的密钥时,我收到错误 Invalid argument supplied for foreach() 。
当我在php 中输出相同的数组索引时,标记@foreach () 循环之前的行,没有错误。
有人可以告诉我为什么会发生这种情况吗?
数组 var_dumped : $item['all']
@php
echo var_dump($item['all']);
die();
@endphp
array (size=1)
0 =>
array (size=22)
'withdraw_prod' => int 0
'class_id' => int 10
'optional' => int 0
'extra' => int 0
'stage' => string 'NA' (length=2)
'pest' => string 'NA' (length=2)
'product' => string 'Monitering' (length=10)
'description' => null
'active' => null
'class' => string 'Ander' (length=5)
'rac_code' => null
'htwoo' => string '0' (length=1)
'prod_ha' => string '2.98' (length=4)
'kgl_ha' => string '0.0000' (length=6)
'hundred_met' => null
'total' => string '0.0000' (length=6)
'cost_kgl' => null
'cost_total' => null
'heading' => null
'header' => int 0
'hex' => null
'is_na' => boolean true
给出错误的下一行代码:
@foreach ($item['all'] as $k => $spray)
一些LOG输出:
<?php $__currentLoopData = $item['all']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $k => $spray): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
Laravel 5.6.39
编辑: 我正在尝试将数据输出到从控制器生成 pdf 的视图:
$pdf = PDF::loadView('direct.tory.here.is.pdf', compact('program', 'taboo', 'colour', 'footnotes'))->setPaper('a4', 'landscape');
视图中的循环是:
@foreach ($program as $key => $item)
@if(!in_array($key, $taboo))
@php
$cnt = 0;
$extra_row = 0;
//echo var_dump($item['all']);
@endphp
@foreach ($item['all'] as $k => $spray)
@php
// for in case array dimensions differ
$sprays = (array_key_exists(0, $spray)) ? $spray[0] : $spray;
if(!empty($sprays['description'])) {
$extra_row++;
}
@endphp
@endforeach
@endif
@php
$col++;
@endphp
@endforeach
解决了
这有点尴尬,但我创建了一个带有禁忌键的数组,该数组从我的主数组$program 中过滤掉了非数组值。对于两个月前的测试,添加了一个包含整数的额外虚拟键 => 值进行测试,但从未添加到禁忌列表中。这个虚拟整数值正在滑过,导致@foreach 循环无法遍历该数组索引不存在的$item['all']。
感谢所有评论者的意见。
【问题讨论】:
-
也许删除
die()?{{ dd($item['all']) }}输出什么? -
它输出相同的数组`array:1 [▼ 0 => array:22 [▼ "withdraw_prod" => 0 "class_id" => 10 "optional" => 0 "extra" => 0“阶段”=>“NA”“害虫”=>“NA”“产品”=>“监控”“描述”=>空“活动”=>空“类”=>“安德”“rac_code”=> null "htwoo" => "0" "prod_ha" => "2.98" "kgl_ha" => "0.0000" "hundred_met" => null "total" => "0.0000" "cost_kgl" => null "cost_total" => null "标题" => null "header" => 0 "hex" => null "is_na" => true ] ]`
-
当你说当我在@foreach()循环之前的行的php标签中输出相同的数组索引时,没有错误你的意思是@中的错误987654337@ 会因为在它之前输出一些东西而消失?
-
@apokryfos 不,我的意思是在
@foreach循环之前输出数组索引不会导致错误(因此索引作为数组存在),但是一旦我尝试访问数组索引在@foreach循环中我收到一个错误。 -
根据您在评论中分享的数据,您的数组中没有任何“all”键。
标签: php arrays laravel foreach laravel-5.6