php计算变量数组中的单词

时间:2015-01-27 05:27:37

标签: php arrays foreach

我有一个变量字符串数组,我想计算所有逗号,并在所有字符串中找到总逗号。我知道我必须使用爆炸和foreach但不知道如何将它们放在一起以及如何在最后添加所有逗号...

 $log1 = "one, two, three,";

 $log2 = "red, blye, green,";

 $log3 = "sunny day, snowy day, nice one,";

 $main_log = array(log1, log2, log3);

5 个答案:

答案 0 :(得分:1)

你想要计算逗号 - 只需这样做:

array_sum(array_map(function($str){
  return substr_count($str, ',');
}, $main_log));

答案 1 :(得分:1)

请做一些更正。连接所有字符串,而不是按照以下代码中的方式将它们推送到数组中;

$log1 = "one, two, three,";

 $log2 = "red, blye, green,";

 $log3 = "sunny day, snowy day, nice one,";

 $main_log = $log1.$log2.$log3;
 echo substr_count($main_log, ','); //prints 9

答案 2 :(得分:0)

substr_count($string, ',');

对于数组.... @vp_arth的解决方案可行......

$log1 = "one, two, three,";

$log2 = "red, blye, green,";

$log3 = "sunny day, snowy day, nice one,";

$main_log = array($log1, $log2, $log3);

$result= array_sum(array_map(function($str){
  return substr_count($str, ',');
}, $main_log));


echo $result;

答案 3 :(得分:0)

像这样修改你的代码 -

$log1 = "one, two, three";
$log2 = "red, blye, green";
$log3 = "sunny day, snowy day, nice one";

$arr1 = explode(',', $log1);
$arr2 = explode(',', $log2);
$arr3 = explode(',', $log3);


$main_log = array_merge($arr1,$arr2,$arr3);   //Array merge
$count = array_count_values($main_log); //Total count the array values

答案 4 :(得分:0)

这是另外两个解决方案:

$log1 = "one, two, three,";
$log2 = "red, blye, green,";
$log3 = "sunny day, snowy day, nice one,";

$main_log = $log1.$log2.$log3;

echo count(explode(',',$main_log))-1;

echo substr_count($main_log, ',');