【问题标题】:Laravel Blade - check if data array has specific keyLaravel Blade - 检查数据数组是否具有特定键
【发布时间】:2018-06-14 12:17:21
【问题描述】:

我需要检查数据数组是否有特定的键,我是这样尝试的:

@if ( ! empty($data['currentOffset']) )
    <p>Current Offset: {{ $currentOffset }} </p>
@else
    <p>The key `currentOffset` is not in the data array</p>
@endif

但我总是得到&lt;p&gt;The keycurrentOffsetis not in the data array&lt;/p&gt;

【问题讨论】:

    标签: laravel laravel-blade


    【解决方案1】:

    你可以使用@isset:

    @isset($data['currentOffset'])
        {{-- currentOffset exists --}}
    @endisset
    

    【讨论】:

    • 还有类似elseisset的东西吗?我需要一个 else 分支。
    • @Black 没有。如果您需要else,您可以使用@if (isset($data['currentOffset'])) 或三元运算符{{ isset($data['currentOffset']) ? 'Exists' : 'Doesn\'t exist' }}
    【解决方案2】:

    我认为你需要这样的东西:

     @if ( isset($data[$currentOffset]) )
     ...
    

    【讨论】:

    • 这正是@Alexey Mezenin 4 分钟前发布的内容。
    • $data[$currentOffset]$data['currentOffset'] 之间没有区别,我想可能密钥存储在变量 $currentOffset 中
    【解决方案3】:

    使用以下:

    @if (array_key_exists('currentOffset', $data))
        <p>Current Offset: {{ $data['currentOffset'] }} </p>
    @else
        <p>The key `currentOffset` is not in the data array</p>
    @endif
    

    【讨论】:

      【解决方案4】:

      三元

       @php ($currentOffset = isset($data['currentOffset']) ? $data['currentOffset'] : '')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-15
        • 1970-01-01
        • 2013-03-15
        • 2011-05-29
        • 1970-01-01
        • 1970-01-01
        • 2019-03-31
        • 1970-01-01
        相关资源
        最近更新 更多