【问题标题】:Laravel Blade - retrieve element by idLaravel Blade - 按 id 检索元素
【发布时间】:2019-03-09 18:03:16
【问题描述】:

我想通过 id 检索一个元素。

在我的刀片文件中:

{{ $auctionStatuses }}

这个输出:

[
    {
        "id":1,
        "name":"Awaiting customer action",
        "created_at":"2018-10-04 10:14:08",
        "updated_at":"2018-10-04 10:14:08"
    },
    {
        "id":2,
        "name":"Transfer in progress",
        "created_at":"2018-10-04 10:15:11",
        "updated_at":"2018-10-04 10:15:11"
    },
    {
        "id":3,
        "name":"Completed",
        "created_at":"2018-10-04 10:15:14",
        "updated_at":"2018-10-04 10:15:14"
    }
] 

id字段引用时想输出名字

由于某些数据来自 mongodb,我无法使用标准关系

我试过这个{{ $auctionStatuses['3'] }} 但这显然不存在。

我想理想情况下,我想做这样的事情

{{ $auctionStatuses[*]->id['3']->name }}

有没有一种方法可以做我需要的事情,而不需要遍历 json 数组?

【问题讨论】:

标签: php json laravel-5.6 laravel-blade


【解决方案1】:

一行:-

$auctionStatuses->toArray()[array_search(3,array_column($auctionStatuses->toArray(),'id'))]['name']

说明

toArray() 将 laravel 集合转换为数组的方法。

array_search 将搜索数组元素并返回索引

array_column 将返回指定列的值

【讨论】:

    【解决方案2】:

    你可以使用:

    $auctionStatuses->firstWhere('id',3)->name;
    

    https://laravel.com/docs/5.7/collections#method-first-where

    【讨论】:

    • 这个答案比我的答案好。
    猜你喜欢
    • 1970-01-01
    • 2013-06-18
    • 2017-12-31
    • 2020-12-25
    • 2021-02-04
    • 2021-01-06
    • 1970-01-01
    • 2021-02-11
    • 2021-11-28
    相关资源
    最近更新 更多