在数组中查找重复的值并将其保存在单独的数组中

编程入门 行业动态 更新时间:2024-10-28 10:34:03
本文介绍了在数组中查找重复的值并将其保存在单独的数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

更多推荐

在数组中查找重复的值并将其保存在单独的数组中

本文发布于:2023-11-22 00:57:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1615346.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中   并将其

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!