如何在 laravel 刀片视图上定义变量数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44529690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:07:49  来源:igfitidea点击:

How can I define variable array on the laravel blade view?

phplaravellaravel-5.3laravel-bladeimplode

提问by Success Man

I try like this :

我尝试这样:

<div class="media-body">
    @foreach($categories as $category)
    @php $category[] = $category->name @endphp
    @endforeach   
    {{ implode(",", $category) }}
</div>

If the code executed, there exist error :

如果代码执行,存在错误:

undefine variable category

取消定义变量类别

How can I solve it?

我该如何解决?

回答by Zayn Ali

You can simply use Laravel Collection

你可以简单地使用 Laravel Collection

{{ $categories->pluck('name')->implode(', ') }}

Or if you wanna do this in foreach then

或者,如果您想在 foreach 中执行此操作,则

@php ($names = [])

@foreach ($categories as $category)
    @php ($names[] = $category->name)
@endforeach

{{ implode(', ', $names) }}

回答by Santhosh J

You have to declare an array within <?php ... ?>block and then use the same in a {{blade}}block.

您必须在<?php ... ?>块中声明一个数组,然后在块中使用相同的数组{{blade}}