Find duplicate values in array and save them in a separate array

断了今生、忘了曾经 提交于 2020-02-23 07:29:10

问题


Bit of a strange one, so I am looking to get all duplicates in an array, and save each of them in a separate array. It's a bit difficult to explain so I will try with an example.

$array = array('apple', 'apple', 'apple', 'orange', 'orange', 'banana');

I am looking to find all duplicates (in this instance, apples and oranges) and save each in their own separate array, which will then be counted afterwards to find out how many of each duplicate exists in each of the arrays.

Once I have counted them, I will then run a mysqli query dependant on the amount found (there can only be a maximum of 6 of the same item).

An example ideal output would be

$array1 to be ('apple', 'apple', 'apple'), $array2 to be ('orange', 'orange') and $array3 would be ('banana')

I apologise in advance if this question doesn't make much sense, but it's pretty difficult for me to explain.


回答1:


$count = [];
$array = ['apple', 'apple', 'apple', 'banana', 'banana', 'orange', 'orange'];

foreach ($array as $a) {
    $count[$a]++;
}

print_r($count);

Array ( [apple] => 3 [banana] => 2 [orange] => 2 )

You could then loop through the one array with key => value obtaining the 'fruit' and occurrence.

Edit: You'll need to uppercase/lowercase the key if you're case-insensitive searching.




回答2:


This could be done with array_count_values() and array_fill() functions

$array = array('apple', 'apple', 'apple', 'orange', 'orange', 'banana');

// counts all the values
$count = array_count_values($array);

// result array
$result = array();

// Loop and push new array filled with values times count
foreach ($count as $key => $value) {
    $result[] = array_fill(0, $value, $key);
}

// Print result
echo '<pre>';
print_r($result);


来源:https://stackoverflow.com/questions/47402882/find-duplicate-values-in-array-and-save-them-in-a-separate-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!