php 在 Laravel 中与 Blade 连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36337108/
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-08-26 00:46:53  来源:igfitidea点击:

Concatenation with Blade in Laravel

phplaraveleloquentlaravel-5.2laravel-blade

提问by Ashley Brown

I'm trying to access a table column in my ItemController. In this instance, I wish to use the values in my array + a concatenated string to for the column name.

我正在尝试访问 ItemController 中的表列。在这种情况下,我希望使用数组中的值 + 连接字符串作为列名。

ItemController.php ....

ItemController.php ....

public function displayItems() {
   $itemsList = array('Alpha','Bravo','Charlie','Delta');
   //$results = returned mysql row here
   return view('items', ['rs' => $results, 'items' => $itemsList]);
}

page.blade.php

页面.blade.php

@foreach ($items as $item)
  //$item is used elsewhere too, so keep $item
  {{$rs->$item.'_data'}}
@endforeach

Desired output:

期望的输出:

$rs->Alpha_data;
$rs->Delta_data;
etc

How can I dynamically set a variable for $rs->name?

如何为 $rs-> name动态设置变量?

回答by Alexey Mezenin

回答by Bruce Tong

lets say you are retrieving a single record 'task', and this record has variables called 'var1','var2','var3' ... all the way to 'var16'.

假设您正在检索单个记录“任务”,并且该记录具有名为“var1”、“var2”、“var3”……一直到“var16”的变量。

you can echo those variables in your blade file like so:

您可以像这样在刀片文件中回显这些变量:

@for($y=1; $y<=16; $y++)
 {{ $task->{'var'.$y} }}
@endfor

回答by Guest-Baby

Quite simple, just use the . sign for concats in PHP

很简单,只要使用 . 在 PHP 中为 concats 签名