php 显示blade laravel上数组项

wxclj1h5  于 2022-12-10  发布在  PHP
关注(0)|答案(2)|浏览(172)

数组:

[
    {"id":1,"group":"post","name":"Mi","value":"x3 poco"},
    {"id":2,"group":"post","name":"iPhone","value":"14 pro"},
    {"id":3,"group":"post","name":"Nokia","value":"C5"},
    {"id":4,"group":"post","name":"Dell","value":"15 insp"}
    .
    .
    .
]

索引控制器.php文件:

$post = Post::all();
return view('index', compact('post'));

索引.blade.php文件:

Post Name: "{{ $post->name['iPhone']->value }}"

我想显示输出如下:

Post Name: "14 pro"

错误是显示:

Error: Property [name] does not exist on this collection instance.
6rqinv9w

6rqinv9w1#

你有一个数组的数组,所以name在一个数字索引里面...
这一点:

[
    {"id":1,"group":"post","name":"Mi","value":"x3 poco"},
    {"id":2,"group":"post","name":"iPhone","value":"14 pro"},
    {"id":3,"group":"post","name":"Nokia","value":"C5"},
    {"id":4,"group":"post","name":"Dell","value":"15 insp"}
    .
    .
    .
]

这是PHP上的:

$array = [
    [
        'id' => 1,
        'group' => 'post',
        'name' => 'Mi',
        'value' => 'x3 poco',
    ],
    [
        // ...
    ],
];

所以,你必须像这样迭代:

Posts:
@foreach ($post as $item)
    Post Name: "{{ $item->value }}"
@endforeach
9vw9lbht

9vw9lbht2#

您可以在集合上使用where来按名称搜索:

Post Name: "{{ $post->where('name', 'iPhone')->first()?->value }}"

问号是在没有项目具有您要查找的名称的情况下。

相关问题