本文介绍了PHP对数组中的重复元素进行计数并结合ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们如何找到多维数组中重复元素的数量以及ID的组合?
How can we find the count of duplicate elements in a multidimensional array and concat of ids ?
我有一系列具有Feed ID的技能名称.我需要计算技能名称和Feed ID的连续性.
I have an array of skill names with feed ids. I need to count skill name and concat of feed ids.
Array
(
[0] => Array
(
[skill_name] => PHP
[feed_id] => 100
)
[1] => Array
(
[skill_name] => CSS
[feed_id] => 105
)
[2] => Array
(
[skill_name] => Php
[feed_id] => 110
)
[3] => Array
(
[skill_name] => Php
[feed_id] => 111
)
[4] => Array
(
[skill_name] => CSS
[feed_id] => 112
)
[5] => Array
(
[skill_name] => Javascript
[feed_id] =>114
)
}
输出应如下所示.
Array
(
[0] => Array
(
[skill_name] => PHP
[feed_id] => 100, 110, 111
[count]=>3
)
[1] => Array
(
[skill_name] => CSS
[feed_id] => 105, 112
[count]=>2
)
[2] => Array
(
[skill_name] => Javascript
[feed_id] => 114
[count]=>1
)
}
提前谢谢!
推荐答案
//Assumption: Input is in $in
//Step 1: Cumulate
$tmp=array();
foreach ($in as $skill) {
if (isset($tmp[$skill['skill_name']]))
$tmp[$skill['skill_name']][]=$skill['feed_id'];
else
$tmp[$skill['skill_name']]=array($skill['feed_id']);
}
//Step 2: Fix up desired output format
$out=array();
foreach ($tmp as $k=>$v)
$out[]=array(
'skill_name' => $k,
'feed_id' => implode(', ', $v),
'count' => sizeof($v)
);
//Result is in $out
这篇关于PHP对数组中的重复元素进行计数并结合ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!