值不止一次出现时的增量计数器


increment counter when value occurs more than once

以下代码的示例输出可能是:

39 48 39 12 17 39 12

代码:

if (mysql_num_rows($filterResult)) {
while ($filterrow = mysql_fetch_array($filterResult)) {
$vidID = $filterrow['routineID'];
...
...
echo "<video id='video$vidID'></video>";
  }
}

我需要像这样输出:

39 48 39_1 12 17 39_2 12_1

注意值39出现了三次,值12出现了两次。在第一次出现一个值之后,我需要它格式为##_#。

你能帮我编一下代码吗?我感谢你的时间和帮助德里克。

像这样使用array_count_values:

$array = array(1, 38, 1, 38,35);
print_r(array_count_values($array));
输出

: -

Array
(
    [1] => 2
    [38] => 2
    [35] => 1
)

应用一些逻辑来实现你想要的

if (mysql_num_rows($filterResult)) {
  $tmp = array();
  while ($filterrow = mysql_fetch_array($filterResult)) {
     $vidID = $filterrow['routineID'];
     if(isset($tmp[$vidID]) {
        $tmp[$vidID] = $tmp[$vidID] + 1;
        $vidID = $vidID . '_' . $tmp[$vidID];
     } else {
        $tmp[$vidID] = 0;
     }
     echo $vidID;
   }
 }
if (mysql_num_rows($filterResult)) {
while ($filterrow = mysql_fetch_array($filterResult)) {
$j=-1;
$vidID = $filterrow['routineID'];
$arr[]=$vidID;
for($i=0;$i<count($arr);$i++){
if($arr[$i]==$vidID)
$j++;
}
if($j==0)
$j="";
else $j="_".$j;
echo $vidID.$j;
 }
}

代码如下:

$array1 = array(39,48,39,12,17,39,12);
$array2 = array(39,48,39,12,17,39,12);
foreach($array1 as $value){
  $counts1 = array_count_values($array1);
  $counts2 = array_count_values($array2);
  if(!empty($counts2[$value])){
    if ($counts1[$value] > 1){
      $count = $counts1[$value] - $counts2[$value] + 1;
              if($count > 1) {
                 echo $value.'_'.($count - 1).' ';
              } else {
                 echo $value.' ';
              }
    } else {
      echo $value.' ';
    }
    array_shift($array2);
  }
}