php数字比较数组

时间:2016-08-29 09:21:14

标签: php arrays

我有考试语言水平的学生 例如:
  (8,8,9,8,7)重复数字“8”得到“8”
  (7,7,8,9,10)重复数字“7”得到“7”
  (7,8,9,10,9)无重复编号获取最后“9”
  (7,7,8,8,9)忘记“7”>获取上次重复次数“8”
  (7,7,8,9,9)忘记“7”>获取最后重复次数“9”

代码在这里

//get duplicate function getArrayDups($array) { $counts = array_count_values($array); return array_filter( $counts, create_function( '$val', 'return($val > 1);' ) ); }

// usage test:
$test = array('8','8','7','7','7');
$result = getArrayDups($test);
    if(count($result))
    {
      echo "<p>You had one or more duplicate entries:</p>\n<ul>\n";
    foreach($result as $entry => $count)
     {
   if ($count >= 3){
     echo "<li> Get Level is  $entry ($count)</li>";
   break;  
   } 
 echo "<li>  Level is $entry ($count)</li>"; 
}
 }
  else
  {
  //echo end($test);
  echo "<li>No duplicates  Level found. last Level." . end($test) . "</li>";
  }

// usage test: $test = array('8','8','7','7','7'); $result = getArrayDups($test); if(count($result)) { echo "<p>You had one or more duplicate entries:</p>\n<ul>\n"; foreach($result as $entry => $count) { if ($count >= 3){ echo "<li> Get Level is $entry ($count)</li>"; break; } echo "<li> Level is $entry ($count)</li>"; } } else { //echo end($test); echo "<li>No duplicates Level found. last Level." . end($test) . "</li>"; }  我想知道是否有人对我如何实现这一目标有任何其他想法。

1 个答案:

答案 0 :(得分:1)

如果explode是一个字符串,您可以使用array_count_values将其转换为数组,并使用$arr = [8,8,9,8,7],如果您的数据已经是数组(如array_count_values),则可以直接使用<?php $str = '8,8,9,8,7'; $arr = explode(',', $str); $arrCount = array_count_values($arr); $temp= false; for($i=count($arr)-1;$i> 0;$i--) { if($arrCount[$arr[$i]] > 1) { echo "last repeat is: ".$arr[$i]; $temp = true; break; } } if(!$temp) echo "no repeat found"; ?>

所以你要做的事情是:

{{1}}