显示json数据以查看为字符串或数组

时间:2018-11-04 03:50:43

标签: php database laravel

Laravel的新手,觉得我在这里错过了一些重要的事情。我正在将多个文件上传并保存到一个文件夹中,并将图像名称数组保存到数据库中(足够简单)。当前以json_encode()格式保存图像名称,因此它们的格式如下["kittyTest.jpeg","kitty_2.jpeg","kitty_3.jpeg"]。因此,当我尝试将它们打印到视图中时,我将它们以json格式获取,并试图以数组形式显示它们,或者以某种方式可以将其用于源图像。任何帮助或指导将不胜感激。

控制器

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Form;
use DB;

class FormController extends Controller
{
 public function index()
{
    $images = DB::select('select * from forms');

    //dd(json_decode($images[0]->filename));

    return view('index', ['images'=> $images]);
}

public function create()
{
    return view('create');
}

public function store(Request $request)
{
    $this->validate($request, [
        'filename' => 'required',
        'filename.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
    ]);

    if ($request->hasFile('filename')) {
        foreach ($request->file('filename') as $image) {
            $name = $image->getClientOriginalName();
            $image->move(public_path().'/images/', $name);
            $data[] = $name;
        }
    }

    $form = new Form();
    $form->filename = json_encode($data);
    $form->save();

    return back()->with('success', 'Your images have been uploaded');
}

}

查看

<body>
<div class="container">


<h3 class="jumbotron">Laravel Multiple File Upload</h3>

<p>Here are the images we have in the database</p>

<ul class="list-group">
@foreach ($images as $image)
    <li class="list-group-item">
        {{ $image->filename }}
    </li>
@endforeach
</ul>
</div>


</body>

2 个答案:

答案 0 :(得分:2)

<ul class="list-group">
@foreach ($images as $image)
    @php $image_array = json_decode($image->filename,true); @endphp
    @foreach ($image_array as $img)
     <li class="list-group-item">

        {{ $img }}
     </li>
    @endforeach
@endforeach
</ul>
try this and let me know

答案 1 :(得分:0)

在您的控制器中,使用array_map对每个图像文件名进行json_decode,然后在视图文件中使用第二个foreach。

控制器

public function index()
{
    $images = DB::select('select * from forms');

    array_map(function($a) { 
        $a->filename = json_decode($a->filename); 
        return $a; 
    }, $images);

    return view('index', compact($images)); // you can use compact function here
}

查看

<ul class="list-group">
@foreach ($images as $image)
    <li class="list-group-item">
        @foreach ( $image->filename as $file)
        {{ $file }}
        @endforeach
    </li>
@endforeach
</ul>

编辑:您也可以尝试使用cast to array,然后不必担心将其映射到控制器文件中。