【问题标题】:How can i rewrite PHP while loop in Laravel Blade我如何在 Laravel Blade 中的循环中重写 PHP
【发布时间】:2021-09-27 11:49:33
【问题描述】:

我是 Laravel 的新手。我有一个用 PHP 编写的循环,但我正在尝试重新开发它以在 Laravel Blade 中使用。所以我有这段代码,我发现很难翻译。我可以从控制器传递$data,但是如何在视图中编写以下代码?

while ($data = $result1->fetch_array()) {
    $dataCount = $data['colCount'];

    for ($x = 0; $x <= $dataCount; $x++) {
        echo "<ul><li>
            <label>
                <input type='radio' name='project-1-response[".$i."]' 
                    value='' />
                    <h7>".$data[$x]."</h7>
            </label> 
            </li></ul>";
    }
}

【问题讨论】:

标签: php laravel laravel-blade laravel-8


【解决方案1】:

在大多数情况下,它非常简单。

  • while(condition) { ... } 替换为
    @while(condition) ... @endwhile
  • for(init; condition; increment) { ... } 替换为
    @for(init; condition; increment) ... @endfor
  • 将您的 php 语句包装在 @php ... @endphp 中,或者如果它是单个语句,
    请使用 @php(statement) 语法。
  • 使用方括号在标记中回显变量或函数。 ({{ $variable }}{{ count($array) }})。

你最终得到

@while($data = $result1->fetch_array())
    @php($dataCount = $data['colCount'])
    @for($x = 0; $x <= $dataCount; $x++)
        <ul>
            <li>
                <label>
                    <input type="radio" name="project-1-response[{{ $i }}]" value="" />
                    <h7>{{ $data[$x] }}</h7>
                </label> 
            </li>
        </ul>
    @endfor
@endwhile

如果 $data 是一个数组,您可以改用 @foreach 循环。您还可以在那里访问$loop 变量。

【讨论】:

    猜你喜欢
    • 2018-04-27
    • 2014-02-24
    • 1970-01-01
    • 2019-11-11
    • 2018-03-31
    • 1970-01-01
    • 2015-11-28
    • 2020-06-22
    • 1970-01-01
    相关资源
    最近更新 更多