在数组中查找重复的值并将其保存在单独的数组中 [英] Find duplicate values in array and save them in a separate array

查看:59
本文介绍了在数组中查找重复的值并将其保存在单独的数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有点奇怪,所以我希望将所有重复项放在一个数组中,并将每个重复项保存在单独的数组中.解释起来有点困难,所以我将尝试一个例子.

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

我正在寻找所有重复项(在这种情况下为苹果和橙子),并将它们保存在各自独立的数组中,然后将其计数,以找出每个数组中存在多少重复项./p>

一旦对它们进行了计数,我将根据找到的数量运行mysqli查询(同一项目最多只能有6个).

一个理想的输出示例是

  $ array1为('apple','apple','apple'),$ array2为('orange','orange')和$ array3为('banana') 

如果这个问题没有多大意义,我事先表示歉意,但是我很难解释.

解决方案

  $ count = [];$ array = ['apple','apple','apple','banana','banana','orange','orange'];foreach($ array as $ a){$ count [$ a] ++;}print_r($ count); 

数组([苹果] => 3[香蕉] => 2[orange] => 2)

然后可以使用key =>值遍历一个数组,以获取果实"和出现的位置.

如果您不区分大小写,则需要大写/小写该键.

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.

解决方案

$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.

这篇关于在数组中查找重复的值并将其保存在单独的数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆