Home  >  Article  >  php教程  >  PHP统计二维数组元素个数的方法

PHP统计二维数组元素个数的方法

WBOY
WBOYOriginal
2016-06-06 20:26:381313browse

数据表里面的字段 content 存储了一个以逗号分割的字符串,最大有20个数,最大数字为40。比如3,24,33,40类似字样的数字序列。其实就是一个保存了多项投票结果的

解决思路
1. 首先从数据库的congtent字段读取数据,,并把它们合并成一个字符串。

复制代码 代码如下:


 while($myrow = $connector -> fetch_array($result))
 {
  //$r[] = explode(",", $myrow["content"]);
  $str .= $myrow["content"].',';
 }

 $arr_str = substr($str, 0, -1);
?>


由于最后一个数后面有逗号,所以要对字符串进行截取。
2. 将字符串按逗号分割成数组。

复制代码 代码如下:


$r = explode(",", $arr_str);


3. 用 array_count_values() 统计一维数组的元素个数
由于array_count_values()貌似不能直接对二维数组的元素进行个数统计,所以进行了上面的两个步骤,得到一个一维数组。
array_count_values() 函数用于统计数组中所有值出现的次数。返回一个数组,其元素的键名是原数组的值,键值是该值在原数组中出现的次数。

复制代码 代码如下:


$rs = array_count_values($r);


4. 排序

复制代码 代码如下:


asort($rs);
echo '

';<br>print_r($rs);<br>echo '
';
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn