Php计算数组中的重复元素和id的连续

时间:2015-02-22 11:22:46

标签: php multidimensional-array count

我们怎样才能找到多维数组中重复元素的数量以及ID的连续数?

我有一系列带有Feed ID的技能名称。我需要计算技能名称和饲料ID的连续数。

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
        )

}

提前致谢!!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

使用临时键以及简单的串联和增量操作,只需一个循环即可完美实现。

代码:(Demo

$array = [
    ['skill_name' => 'PHP', 'feed_id' => 100],
    ['skill_name' => 'CSS', 'feed_id' => 105],
    ['skill_name' => 'Php', 'feed_id' => 110],
    ['skill_name' => 'Php', 'feed_id' => 111],
    ['skill_name' => 'CSS', 'feed_id' => 112],
    ['skill_name' => 'Javascript', 'feed_id' => 114]
];

foreach ($array as $row) {
    $upperSkill = strtoupper($row['skill_name']);
    if (!isset($result[$upperSkill])) {
        $result[$upperSkill] = $row + ['count' => 1];  // plus acts as array_merge here
    } else {
        $result[$upperSkill]['feed_id'] .= ",{$row['feed_id']}"; // concatenate
        ++$result[$upperSkill]['count'];  // increment
    }
}
var_export(array_values($result));  // reindex and display

输出:

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