问题描述
Laravel 的 foreach
和 forelse
的基本区别是什么?forelse
是如何工作的?
What's the basic difference between Laravel's foreach
and forelse
? How does forelse
work?
我知道 foreach
复制您给定的数组并对其进行处理,而在 forelse
中,它检查它是否存在并在它存在时循环,如果不存在则使用您的提供其他条件.
I know that foreach
duplicates your given array and works on it while in forelse
it checks whether it exists and loops on it if it exists but if not it uses your provided else condition.
推荐答案
我相信您的问题的答案是,本质上 ForElse 是 一个 ForEach 循环,但对空数组进行了额外处理.
I believe the answer to your question is that, essentially, ForElse is a ForEach loop, but with extra handling for empty array.
来自 Laravel 5 文档中关于 Blade 模板的示例,说明了使用相同用户列表作为输入的两个循环:
From the Laravel 5 docs on Blade Templates, an example illustrating both loops with the same list of Users as Input:
@foreach ($users as $user)
<p>This is user {{ $user->id }}</p>
@endforeach
@forelse ($users as $user)
<li>{{ $user->name }}</li>
@empty
<p>No users</p>
@endforelse
现在,如果我们将其与 Laravel 框架的源代码进行比较,以查看循环是如何编译的(所有 Blades 构造在网页上由 PHP 呈现时都被编译为 HTML):
Now if we compare this to the source code for the Laravel Framework to see how the loops are compiled (all Blades constructs are compiled into HTML when being rendered by PHP on the web page):
/**
* Compile the for-each statements into valid PHP.
*
* @param string $expression
* @return string
*/
protected function compileForeach($expression)
{
preg_match('/( *(.*) +as *(.*))$/is', $expression, $matches);
$iteratee = trim($matches[1]);
$iteration = trim($matches[2]);
$initLoop = "$__currentLoopData = {$iteratee}; $__env->addLoop($__currentLoopData);";
$iterateLoop = '$__env->incrementLoopIndices(); $loop = $__env->getLastLoop();';
return "<?php {$initLoop} foreach($__currentLoopData as {$iteration}): {$iterateLoop} ?>";
}
/**
* Compile the for-else statements into valid PHP.
*
* @param string $expression
* @return string
*/
protected function compileForelse($expression)
{
$empty = '$__empty_'.++$this->forElseCounter;
preg_match('/( *(.*) +as *(.*))$/is', $expression, $matches);
$iteratee = trim($matches[1]);
$iteration = trim($matches[2]);
$initLoop = "$__currentLoopData = {$iteratee}; $__env->addLoop($__currentLoopData);";
$iterateLoop = '$__env->incrementLoopIndices(); $loop = $__env->getLastLoop();';
return "<?php {$empty} = true; {$initLoop} foreach($__currentLoopData as {$iteration}): {$iterateLoop} {$empty} = false; ?>";
}
本质上,ForElse 循环有一个内置代码并编译检查空输入,在这种情况下,它可以选择为空输入输出一个备用显示模板.
Essentially, the ForElse loop has a built-in code and compile check for an empty input, in which case it optionally outputs an alternate display template for the empty input.
我想你可以在任何可能使用 ForElse 循环的情况下使用 ForEach 循环,并补充说你包含和清空 ForElse 可能为你捕获的检查.
I would imagine you can use a ForEach loop in every case that you might use a ForElse loop, adding that you include and empty checks that ForElse might catch for you.
参考链接:
这篇关于Laravel 中 foreach 和 forelse 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!