dspld86684 2019-01-26 23:35
浏览 54
已采纳

如何将我的数字串输入数组以获得最常见的数字? [重复]

This question already has an answer here:

I'm using PHP Codeigniter, and I'm trying to get a string of numbers that are in a single variable to an array where it will produce the most frequent number.

I'm trying to do this but it doesn't seem to work.

$string_of_numbers = "1, 2, 4, 5, 6, 3, 2, 2, 1, 4, 4, 4";    

$numbers = [$string_of_numbers];

But this works

$numbers = [1, 2, 4, 5, 6, 3, 2, 2, 1, 4, 4, 4];

I think I'm supposed to convert those string numbers into an interval, but I'm not sure how.

$strong_of_numbers = "1, 2, 4, 5, 6, 3, 2, 2, 1, 4, 4, 4";
$numbers = [$strong_of_numbers ]; 




$count = array_count_values($numbers); 
// get count of occurrence for each number

arsort($count); 
// sort by occurrence, descending

$first = key($count); 
// get key of first element, because that is the/one

$count_first = current($count); 
// get occurrence for first array value

$count_second = next($count); 
// get occurrence for second array value

if($count_first != $count_second) { 
// did they occur in different frequencies?

    echo $first . ' occurred most in input array.';
        } else {
    echo 'input array contained multiple values with highest occurrence.';
    }

End result is that $numbers should accept the $strong_of_numbers as integers, and show the most common/frequent integer.

</div>
  • 写回答

3条回答 默认 最新

  • duanhao5038 2019-01-26 23:43
    关注

    Use explode() to build your array, based on the delimiter ", " :

    $string_of_numbers = "1, 2, 4, 5, 6, 3, 2, 2, 1, 4, 4, 4";    
    
    $numbers = explode(", ", $string_of_numbers);
    
    var_dump($numbers);
    

    Output

    array (size=12)
      0 => string '1' (length=1)
      1 => string '2' (length=1)
      2 => string '4' (length=1)
      3 => string '5' (length=1)
      4 => string '6' (length=1)
      5 => string '3' (length=1)
      6 => string '2' (length=1)
      7 => string '2' (length=1)
      8 => string '1' (length=1)
      9 => string '4' (length=1)
      10 => string '4' (length=1)
      11 => string '4' (length=1)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题