PHP - 删除数组中的所有重复项

问题描述 投票:1回答:3

如何从多个阵列中删除重复项?

pinkycocos在我的阵列中是双倍的。必须删除所有双重的单词。如果删除了这些,我会将这些单词放在我的选择中。我从我的数据库中得到这些词。

查询:

$queryClient = " SELECT DISTINCT `clients` FROM `reps` WHERE `clients` != ''";

这是我的代码:

while($row =  mysql_fetch_assoc($resultClient)){
    $names = explode(",", $row['clients']);
    echo '<pre>'; print_r($names); echo '</pre>';
}

结果:(那些食物词只是一个例子)

Array
    (
        [0] => chocolate
    )
    Array
    (
        [0] => vanilla
        [0] => cocos
    )
    Array
    (
        [0] => strawberry
    )
    Array
    (
        [0] => pinky
        [1] => watermelon
        [2] => melon
        [3] => cocos
    )
    Array
    (
        [0] => pinky 
    )
    Array
    (
        [0] => dark-chocolate
    )

我在我的while循环中尝试了这个但它不起作用:

$array = array_unique($names, SORT_REGULAR);

如何删除所有重复项?你能帮助我,还是解决我的问题?救命。

php arrays array-unique
3个回答
4
投票

这是一个单行:

print_r(array_unique(call_user_func_array('array_merge', $names)));

首先将所有子阵列合并为一个,然后获得唯一值。

完整示例:

$names = array();
while($row =  mysql_fetch_assoc($resultClient)){
    $names[] = explode(",", $row['clients']);
}
print_r(array_unique(call_user_func_array('array_merge', $names)));

1
投票

你可以做一个小技巧:

展平,计数然后删除除最后一个之外的所有内容。

$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array)); 
$flatArray = [];
foreach($it as $v) {
   $flatArray[] = $v;           //Flatten array
}

//Note you can do array_unique on the flat array if you also need to flatten the array

$counts = array_count_values($flatArray); //Count 

foreach ($array as &$subarray) {
     foreach ($subarray as $index => $element) {
          $counts[$element]--;
          if ($counts[$element] > 0) { //If there's more than 1 left remove it
               unset($subarray[$index]);
          }
     }
} 

这将删除完全嵌套在第二级上的重复项,而不会展平原始数组。

http://sandbox.onlinephpfunctions.com/code/346fd868bc89f484dac48d12575d678f3cb53626


1
投票

首先,您需要加入数组才能过滤掉重复项:

<?php
$allNames = [];
while($row =  mysql_fetch_assoc($resultClient)){
    $names = explode(",", $row['food']);
    $allNames[] = $names;
}

$allNames = array_merge(...$allNames);  //Join everything to a one dimensional array
$allNames = array_unique($allNames); // Only keep unique elementes

print_r($allNames);
© www.soinside.com 2019 - 2024. All rights reserved.