如何从PHP对象数组中获取数据?

时间:2019-11-13 10:44:20

标签: php html laravel

在数据库表-about_us中,我有一列名为subject

我正在尝试使用laravel中的数据制作表格

subject看起来像这样:

[
    {
        "name1": "1",
        "name2": "2"
    },
    {
        "name1": "3",
        "name2": "4"
    }
]

来自控制器

public function about()
{
    $about  = About::find(1);
    return view('pages.about-us', compact('about'));
}

about-us.blade.php

{{$about->subject}}

如何提取数据以制成这样的表? enter image description here

4 个答案:

答案 0 :(得分:2)

您的subject属性的内容是一个JSON字符串。这意味着您必须先通过json_decode()将其解码为数组/对象,然后才能对其进行迭代。

<table>
    <thead>
        <tr>
            <th>right</th>
            <th>left</th>
        </tr>
    </thead>
    <tbody>
        @foreach(json_decode($about->subject) as $subject)
            <tr>
                <td>{{ $subject->name1 }}</td>
                <td>{{ $subject->name2 }}</td>
            </tr>
        @endforeach
    </tbody>
</table>

答案 1 :(得分:1)

请尝试以下代码:

<table>
    <tr>
        <td>right</td>
        <td>left</td>
    </tr>
    @foreach(json_decode($about->subject) as $subject)
        <tr>
            <td>{{ $subject->name1 }}</td>
            <td>{{ $subject->name2 }}</td>
        </tr>
    @endforeach
</table>

答案 2 :(得分:0)

<table>
<thead>
    <th><strong>right</strong></th>
    <th><strong>left</strong></th>
</thead>
<tbody>
@foreach($about->subject as $subject)
        <tr>
            <td>{{ $subject->name1 }}</td>
            <td>{{ $subject->name2 }}</td>
        </tr>
    @endforeach
</tbody>
</table>

只需遍历数据

答案 3 :(得分:0)

尝试一下

<table>
<thead>
      <tr>
        <th>Right</th>

        <th>Left</th>

       </tr>
</thead>
<tbody>
@foreach($about->subject as $subject)
    <tr>
        <td>{{ $subject->name1 }}</td>
        <td>{{ $subject->name2 }}</td>
    </tr>
@endforeach


</tbody>
</table>