【问题标题】:PHP: Count different numbers in stringPHP:计算字符串中的不同数字
【发布时间】:2016-05-14 15:57:52
【问题描述】:

我得到一个这样的字符串:

,10,10,10,10,10,10,10,11

我如何计算有多少个不同的数字?

【问题讨论】:

标签: php


【解决方案1】:
//remove the starting from the given string,
$input = substr($input, strpos(',', $input) + 1);

//split the string on ',' and put it in an array
$numbers = explode(',', $input);

//an array to put our unique numbers in
$counter = array();
//for each number
foreach($numbers as $number) {
  //check if it is not in the unique 'counter' array
  if(!in_array($number, $counter)) {
    //remember this unique number
    $counter[] = $number;
  }
}

//count the unique number array
$different = count($counter);
//give some output
echo "There are " . $different . " unique numbers in the given string";

输入变量应该是您的文本,因为您的文本以“,”开头,我们将其从输入字符串中删除

【讨论】:

  • 谢谢。那行得通。顺便说一句:不是“子字符串”。它是“substr”。但有了它,它就奏效了。
【解决方案2】:

您可以使用explode 函数将string 设为一个数组,然后在其上使用array_unique 函数来获取它的唯一编号。从这个数组数组中,您可以轻松计算出您的数字中有多少是唯一的。

$str = ",10,10,10,10,10,10,10,11";

$arr = explode(",", trim($str, ","));

$arr = array_unique($arr);

print_r($arr);

结果:

Array
(
    [0] => 10
    [7] => 11
)

现在是时候数了,只需使用count

echo count($arr);// 2

【讨论】:

    【解决方案3】:
    1. explodestring,
    2. array_filter 没有回调,删除空匹配(第一个逗号)
    3. array_unique 删除重复值
    4. count 返回array_unique 的大小

    $string = ",10,10,10,10,10,10,10,11";
    echo count(array_unique(array_filter(explode(",", $string))));
    

    【讨论】:

    • 想评论 DV 吗?
    • 他没有。我对这个家庭作业问题投了反对票,并对你的答案投了赞成票。这里最简单有效。 - 我个人使用 array_map(intval,...) 而不是 array_filter(...)。
    【解决方案4】:

    试试这样的:

    $string = '10, 10, 11, 11, 11, 12';
    
    $numbers = explode(',',$string);
    $counter = array();
    foreach($numbers as $num) {
       $num = trim($num);
       if (!empty($num)) {
          if (!isset($counter[$num])) {
             $counter[$num]=1;
          } else {
             $counter[$num]++;
          }
       }
    }
    
    print_r($counter);
    

    希望对您有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-20
      相关资源
      最近更新 更多