【问题标题】:Laravel DB query to arrayLaravel DB 查询到数组
【发布时间】:2018-08-25 08:39:41
【问题描述】:

我将“hello,world”作为数组存储在 mysql 数据库中,然后尝试使用以下查询检索

 @php
    $post_id = $post->id;
    $result= DB::table('posts')
    ->select('tags')
    ->where('id', '=',  $post_id)
    ->get();

    echo($result);

 @endphp

回显的结果是:

[{"tags":"hello,world"}] 

我需要为上述结果回显单个值

hello 

world

【问题讨论】:

  • 这在 Laravel 文档中的“运行选择查询”laravel.com/docs/5.6/database#running-queries987654321@ 中有解释
  • 我检查过但找不到任何解决方案
  • 字面意思是:“select 方法将始终返回一个结果数组。数组中的每个结果都是一个 PHP StdClass 对象,允许您访问结果的值。”
  • 你能帮我用 foreach 什么的吗

标签: mysql arrays laravel object type-conversion


【解决方案1】:
@php
    $post_id = $post->id;
    $result= DB::table('posts')
    ->select('tags')
    ->where('id', '=',  $post_id)
    ->first();

  $tags = $results->tags;
  $tagsArray =  explode(',', $tags);
 @endphp

现在

@foreach($tagsArray as $ta)
{{ $ta }} <br />

@endforeach

你的输出将是

你好

世界

【讨论】:

    【解决方案2】:
    @php
    $post_id = $post->id;
    $result= DB::table('posts')
                  ->select('tags')
                  ->where('id', '=',  $post_id)
                  ->get();
    
    echo($result[0]->tags);
    @endphp
    

    这段代码会给你输出:

    hello,world
    

    可以使用字符串split()函数,查看函数手册here

    【讨论】:

      猜你喜欢
      • 2017-06-30
      • 2017-06-14
      • 1970-01-01
      • 2013-10-06
      • 1970-01-01
      • 1970-01-01
      • 2021-03-02
      • 2017-11-17
      • 2018-04-06
      相关资源
      最近更新 更多