【问题标题】:How to compare variables in blade template如何比较刀片模板中的变量
【发布时间】:2016-07-15 13:26:38
【问题描述】:

大家好, 我试图比较刀片模板中的 2 个变量

我的控制器

$files = \File::files('images');

     foreach ($files as $file) {
          $info[] = pathinfo($file);
     }

$books = File::where('status', 1)->select('name')->get();

return view('cataloged.read', compact(['info','books']));

在我看来 试试这样的

@foreach($info as $inf)
 @if(isset($books))
     @if($inf['basename'] == $books->name)
         Match
     @else
         No Match
     @endif
 @endif  
@endforeach

这项工作仅适用于最后一条记录 - 我的数据库中有 2 条记录 - 所以在这种情况下它只适用于第二条记录......

我该怎么办?

感谢大家的帮助!

编辑

 @foreach($books as $book)
           @foreach($info as $file)
              @if($book->name == $file['basename'])
                <p>Book</p>
              @else
                <p>No Book</p> 
              @endif
           @endforeach
  @endforeach

我的数据库中只有 4 本书,所以这很好用

@if($book->name == $file['basename'])
       <p>Book</p>
@endif

书 书 书 预订

但是当我使用@else 时,我会像这样开始 没有书 6 次 没有书 6 次 没有书 6 次 书没书6次

【问题讨论】:

  • Books 是一个数组,因此您也需要对其进行迭代
  • 两个文件在同一个目录下?

标签: laravel laravel-5.2 blade


【解决方案1】:

因为,$books 也是数组。您可能应该这样做:

@foreach($info as $inf)
    @if(isset($books))
        @foreach($books as $book)
            @if($inf['basename'] == $book->name)
                Match
            @else
                No Match
            @endif
        @endforeach
    @endif
@endforeach

编辑

<?php
    $i = 0;
    $count = count($books);
?>
    @foreach($info as $file)
        @if(($i<$count)?($books[$i]->name == $file['basename']):false)
            <p>Book</p>
        @else
            <p>No Book</p>
        @endif
        <?php $i++ ?>
    @endforeach

但是,如果这本书不应该在数组中,那么您应该写 File::where('status', 1)-&gt;select('name')-&gt;first(); 而不是 File::where('status', 1)-&gt;select('name')-&gt;get();

【讨论】:

  • 我做了,但它不起作用:(而且我不知道为什么......真的很奇怪的一天
  • 我已编辑并提供了新的编辑。所以,请检查它是否有效。
  • 不工作的人...未定义的偏移量:4 我尝试了 @while($i
  • 出现该错误是因为书的数量和文件的数量不同。如果它们不同,那么使用它也没有用。此代码仅在书籍记录数和文件基本名称数相同时才有效。所以,我再次更改了编辑代码。请尝试..它可能会工作
  • 哦,伙计,那真的很接近...开始 Bookx2 和 No Boox x5
猜你喜欢
  • 2014-12-08
  • 1970-01-01
  • 1970-01-01
  • 2013-05-06
  • 2017-02-08
  • 1970-01-01
  • 1970-01-01
  • 2020-08-21
  • 2016-05-25
相关资源
最近更新 更多