如何从多个数组中删除重复的键和值

时间:2019-06-10 12:50:23

标签: php laravel foreach

我具有多重数组功能,需要从视图中的数组中删除重复值并显示在列表中。

数组尝试删除“ mfgg_name”(如果出现超过1次)

array:44 [▼
 0 => array:4 [▼
   "mfgg_name" => "Solomon Colors, Inc."
   "mfgg_id" => 122
   "product_name" => "Lythic Protector"
   "product_id" => 2586
 ]
 1 => array:4 [▼
   "mfgg_name" => "Solomon Colors, Inc."
   "mfgg_id" => 122
   "product_name" => "Lythic SPD Protector"
   "product_id" => 2587
 ]
 2 => array:4 [▼
   "mfgg_name" => "Solomon Colors, Inc."
   "mfgg_id" => 122
   "product_name" => "Lythic Cleaner"
   "product_id" => 2588
 ]
 3 => array:4 [▼
   "mfgg_name" => "Solomon Colors, Inc."
   "mfgg_id" => 122
   "product_name" => "Lythic DAY1 Hardener"
   "product_id" => 2589
 ]

     @if(count($list_all_active_manufacturers) > 0 ) 

                                 {{dd($list_all_active_manufacturers)}}
                                    @foreach($list_all_active_manufacturers as $leedsManufacturer)
                                <div class="post" id="post{{$leedsManufacturer['mfgg_id']}}">
                                    <label class=" my-checkbox gry2" id="manufacturer">{{str_limit($leedsManufacturer['mfgg_name'], 300)}}
                                        <input type="checkbox" class="manufacturer common_selector" name="manufacturer[]" value="{{$leedsManufacturer['mfgg_id']}}">
                                        <span class="checkmark"></span>
                                    </label>
                                </div>

                                    @endforeach 
                                @endif

2 个答案:

答案 0 :(得分:0)

那里可能有更好的答案,但这是我根据数据质量要做的-

foreach ($test as $key => $value) {
    unset($test[$key + 1]['mfgg_name']);
}

它所做的是保留名称为第一个数组,但之后将其删除为所有数组-然后我将执行isset()来检查输出中是否存在

@if(count($list_all_active_manufacturers) > 0 ) 
    @foreach($list_all_active_manufacturers as $leedsManufacturer)
        <div class="post" id="post{{$leedsManufacturer['mfgg_id']}}">
            @if(isset($leedsManufacturer['mfgg_id]))
                <label class=" my-checkbox gry2" id="manufacturer">{{str_limit($leedsManufacturer['mfgg_name'], 300)}}
                <input type="checkbox" class="manufacturer common_selector" name="manufacturer[]" value="{{$leedsManufacturer['mfgg_id']}}">
                <span class="checkmark"></span>
                </label>
            @endif
        </div>
     @endforeach 
@endif

这未经测试,但是可能会让您步入正轨-如果isset()不起作用,您可以尝试($leedsManufacturer['mfgg_name'] > 0)@if(array_key_exists('mfgg_name', $leedsManufacturer)

答案 1 :(得分:0)

您可以使用此功能,

function unique_multidim_array($array, $key)
{
    $temp_array = [];
    $i          = 0;
    $key_array  = [];
    foreach ($array as $val) {
        if (!in_array($val[$key], $key_array)) {
            $key_array[$i]  = $val[$key];
            $temp_array[$i] = $val;
        }
        $i++;
    }
    return $temp_array;
}
// unique by mfgg_name
$result = unique_multidim_array($yourArr,'mfgg_name');