我正在循环浏览具有所有可用配置选项的产品。在我循环浏览我的项目的内部,当我在产品中得到匹配时,我想显示这个产品和项目。
为此,我想创建一个名为$currentProduct的变量。
@foreach($order['products'] as $product) // Configurable products
@foreach($order['items'] as $item) // Simple products
@if ($item['product_type'] == 'simple')
@if ($product['id'] === $item['product_id'])
@php($currentProduct = $product) // error here $product undefined
@php($currentItem = $item) // error here $item undefined
@endif
@elseif ($item['product_type'] == 'configurable')
@if ($product['id'] == $item['parent_item']['product_id'])
@php($currentProduct = $product) // error here $product undefined
@php($currentItem = $item) // error here $item undefined
@endif
@endif
@endforeach
@endforeach
我是laravel和blade模板的新手,似乎无法理解为什么$product和$item在同一模板的正上方定义时是未定义的。
感谢的任何帮助
您将代码放在@php
和@endphp
之间,但没有附带条件
您可能会成功使用$loop
变量:
@foreach($order['products'] as $product) // Configurable products
@foreach($order['items'] as $item) // Simple products
@if ($item['product_type'] == 'simple')
@if ($product['id'] === $item['product_id'])
@php
$currentProduct = $order['products'][$loop->parent->index];
$currentItem = $order['items'][$loop->index];
@endphp
@endif
@elseif ($item['product_type'] == 'configurable')
@if ($product['id'] == $item['parent_item']['product_id'])
@php
$currentProduct = $order['products'][$loop->parent->index];
$currentItem = $order['items'][$loop->index];
@endphp
@endif
@endif
@endforeach
@endforeach
然后可以在定义变量的地方使用这些变量。
参见文档:
$loop
属性:https://laravel.com/docs/master/blade#the-循环变量- 刀片模板中的原始PHP:https://laravel.com/docs/8.x/blade#raw-php
任何@php都必须使用@endphp 关闭
请尝试下面的代码好吗?`
@foreach($order['products'] as $product)
@foreach($order['items'] as $item)
@if ($item['product_type'] == 'simple')
@if ($product['id'] === $item['product_id'])
@php ($currentProduct = $product) @endphp
@php ($currentItem = $item) @endphp
@endif
@elseif ($item['product_type'] == 'configurable')
@if ($product['id'] == $item['parent_item']['product_id'])
@php ($currentProduct = $product) @endphp
@php ($currentItem = $item) @endphp
@endif
@endif
@endforeach
@endforeach
`