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

PHP - Delete all duplicates in array

如何从多个数组中删除重复项?

pinkycocos 在我的数组中是双倍的。所有重复的单词都必须删除。如果那些被删除,我会把这些话放在我的 select 中。 我从我的数据库中得到这些词。

查询:

$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);

如何删除所有重复项?你能帮我吗,或者你有解决我问题的方法吗?帮助。

这里有一条线:

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)));

你可以做个小动作:

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

$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]);
          }
     }
} 

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

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

首先你需要加入你的数组,然后才能过滤掉重复项:

<?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);