【问题标题】:Laravel: Array to StringLaravel:数组到字符串
【发布时间】:2021-08-24 14:59:37
【问题描述】:

这是我获取子类别名称的代码。但问题是它以数组形式显示数据。

$couponCategory = Coupon::select('categories')->where('expiry_date', '>', $dt)->where('status', 1)->first();
$couponsCat = explode(',', $couponCategory);

$categoriesDetails = Category::select('category_name')->whereIn('id', $couponsCat)->whereNotIn('parent_id', [0, 0])->get()->toArray();
str_replace("'", "\'", json_encode($categoriesDetails));

echo "<pre>";
print_r($categoriesDetails);
die;

结果

Array
(
    [0] => Array
        (
            [category_name] => Casual T-Shirts
        )

    [1] => Array
        (
            [category_name] => Formal T-Shirt
        )

)

我也尝试将其转换为字符串,但输出类似于

[{"category_name":"Casual T-Shirts"},{"category_name":"Formal T-Shirt"}]

我希望结果只显示名称 Casual T-Shirts 和 Formal T-Shirt 没有括号或任何字符串格式

【问题讨论】:

  • 它是一个数组,把它当作一个数组来对待
  • 以简单字符串显示的可能方式??
  • foreach($categoriesDetails as $cat) { echo $cat['category_name']; }
  • 非常感谢@RiggsFolly
  • 到目前为止你尝试过什么?你被困在哪里了?通过简单的调试,应该可以查到这个

标签: php mysql laravel laravel-query-builder


【解决方案1】:

Laravel 集合可以轻松内爆:

echo $categoriesDetails->map->category_name->join(' ');

【讨论】:

    【解决方案2】:

    您可以使用pluck 以基本数组格式获取您想要的字段:

    $categoryNames = Category::whereIn('id', $couponsCat)
      ->whereNotIn('parent_id', [0, 0])
      ->pluck('name');
    

    然后使用普通的旧 PHP 刀片循环遍历结果。

    @foreach ($categoryNames as $name)
      {{ $name }}
    @endforeach
    
    foreach ($categoryNames as $name) {
      echo $name;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-04
      • 2016-07-08
      • 2016-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-14
      • 2020-09-10
      相关资源
      最近更新 更多