一、查询字符串在数组中出现的次数

<?php 

$array = array(1, "hello", 1, "world", "hello","11");
//计算$string在$array(需为数组)中重复出现的次数
function get_array_repeats(array $array,$string) {

$count = array_count_values($array);
//统计中重复元素的次数,再重组数组,
//打印array_count_values($array)出,结果:
//Array(
// [1] => 2
// [hello] => 2
// [world] => 1
//)
if (key_exists($string,$count)){
return $count[$string];
}else{
return 0;
}
}
$string="11";
echo get_array_repeats($array,$string);

?>

查询字符在字符串中出现的次数

<?php
$colors= array('red','blue','green','yellow','red');
$str = implode(',',$colors);//转为字符串
$count=substr_count($str,'red');
echo $count;
?>


 

二、php中统计一维数组相同元素出现的的次数,可以用php自带的函数array_count_values

用法示例如下:

$a =array("A","Cat","Dog","A","Dog");
$a = array_count_values($a);
print_r($a);

运行输出打印结果如下:

Array
(
[A] => 2
[Cat] => 1
[Dog] => 2
)

当然如果你不想使用PHP自带的函数,也可以自己实现,实例如下:

function arr_count_v($arr){
$newArr = array();
foreach ($arr as $k => $v) {
if(empty($newArr[$v])){
$newArr[$v] = 1;
}else{
$newArr[$v] ++;
}
}
return $newArr;
}

$a =array("A","Cat","Dog","A","Dog");
$a = array_count_v($a);
print_r($a);

打印结果:

Array
(
[A] => 2
[Cat] => 1
[Dog] => 2
)