简体   繁体   English

从数据库列获取唯一值(每个单元格都有逗号分隔的值)

[英]Get unique values from database column (each cell has comma separated value)

I'm trying to get unique values as list option from database column through foreach where each cell has multiple values seperated by comma. 我正在尝试通过foreach从数据库列中获取唯一值作为列表选项,其中每个单元格具有多个用逗号分隔的值。

Database cell: 数据库单元:

  1. Door, Window 门,窗
  2. Window, Sheet 窗,板
  3. Sheet, Door 板,门

I'm trying to get the following as the select option: 我正在尝试将以下内容作为选择选项:

  1. Door
  2. Window 窗口
  3. Sheet

I'm using laravel and and tryied the follwing: 我正在使用laravel并尝试了以下方法:

My controller looks like: 我的控制器看起来像:

$products = DB::table('dealers')->select('products')->distinct()->get();

My blade view looks like: 我的刀片视图如下所示:

<select>
<option value="">All</option>
@foreach( $products as $product)
    <?php
    foreach(explode(", ", $product->products) as $value)

        printf(
            '<option value="%1$s">
                                    %1$s
                                </option>',
            $value
        );
    ?>
@endforeach

I'm getting the following output as: [1] Door [2] Window [3] Window [4] Sheet [5] Sheet [6] Door 我得到以下输出:[1]门[2]窗口[3]窗口[4]工作表[5]工作表[6]门

Can anyone please help! 谁能帮忙! I need to make it: [1] Door [2] Window [3] Sheet 我需要做到:[1]门[2]窗口[3]板料

PHP has a large standard library of array functions, including array_unique PHP具有大型的数组函数标准库,包括array_unique

EDIT 编辑

I missed the outer loop. 我错过了外循环。 You have to get unique-ness for the whole data set, not just per-row 您必须获得整个数据集的唯一性,而不仅仅是每行

$uniqueProducts = array_unique(array_merge(...array_map(function($row) {
   return explode(', ', trim($row));
}, $products));

Simple you can save each term in array. 很简单,您可以将每个术语保存在数组中。 then check if not value exists in array. 然后检查数组中是否不存在值。 Try laravel blade view code below: 尝试以下laravel刀片视图代码:

<select>
    <option value="">All</option>
    <?php $array = []; ?>
    @foreach( $products as $product)
        @foreach(explode(", ", $product->products) as $value)
            @if(!in_array($value, $array))
            <option value="{{ $value }}">{{ $value }}</option>
            @endif
        @endforeach
    @endforeach
</select>

是为我工作的东西!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM