【问题标题】:Output json data from database Laravel into separate input fields将数据库 Laravel 中的 json 数据输出到单独的输入字段中
【发布时间】:2018-10-08 20:09:54
【问题描述】:

所以我有多个输入以 json 格式保存到数据库中的一列中,并在检索时将该 json 转换为数组以输出正确的数据。

<input type="text" name="waypoints" class="form-control" autocomplete="on" value="{{ json_decode($myroute->waypoints, true)[0] }}">

上面的代码是输入中显示的数组中的第一项,所以如果我在哪里列出

{{ json_decode($myroute->waypoints, true)[0] }}
{{ json_decode($myroute->waypoints, true)[1] }}
{{ json_decode($myroute->waypoints, true)[2] }}

它会正确输出数组。但是,我如何计算出数组中有多少并且只显示正确数量的输入字段? (最多 10 个)

我尝试在输入字段周围使用@foreach ($myroutes as $myroute)@endforeach,但收到一条错误消息。

提前致谢!

【问题讨论】:

    标签: arrays json database laravel laravel-5


    【解决方案1】:

    你可以这样做:

    @foreach(json_decode($myroute->waypoints, true) as $v)
    
      <input type="text" name="waypoints[]" class="form-control" autocomplete="on" value="{{ $v }}">
    
    @endforeach
    

    但是,如果您可以使用数组而不是 json 响应来响应,那就更容易了。

    像这样:

    return view('edit')-&gt;with('myroutes', json_decode($myroute-&gt;waypoints, true));

    在你看来:

    @foreach ($myroutes as $v) 
    
        <input type="text" name="waypoints[]" class="form-control" autocomplete="on" value="{{ $v }}">
    
    @endforeach
    

    【讨论】:

    • 你确定你的数据是json类型的吗?
    • 刚刚注意到它在有多个输入时有效,但如果只有一个航路点,它会显示该错误。应该注意航点也可以为空。
    • 快速解决方案:@foreach(json_decode($myroute-&gt;waypoints, true) ?? [] as $v)
    • @devk 谢谢!。是的,这将是一个很好的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2018-03-21
    • 2015-05-23
    • 2018-10-07
    • 2023-03-13
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 2019-07-10
    相关资源
    最近更新 更多