Home >Backend Development >PHP Tutorial >PHP 统计一维数组value雷同的元素的个数num,并将其转化为下标为数字,值是value和num的二维数组

PHP 统计一维数组value雷同的元素的个数num,并将其转化为下标为数字,值是value和num的二维数组

WBOY
WBOYOriginal
2016-06-13 12:01:26966browse

PHP 统计一维数组value相同的元素的个数num,并将其转化为下标为数字,值是value和num的二维数组

最近做一个项目,从数据库查询某个字段得到一个数组key是数字值是channel的一维数组$res,现需要将这个数组变成键是数字值是channel和num(num为相同channel的数量,默认为0)。

$res数组

array (size=2)  0 => string '0' (length=1)  1 => string '500000009' (length=9)  2 => string '500000009' (length=9)
$rs数组

array (size=2)  0 => int 1  500000009 => int 2

$arr数组

array (size=2)  0 =>     array (size=2)      'channel' => int 0      'num' => int 1  1 =>     array (size=2)      'channel' => int 500000009      'num' => int 2


处理代码

foreach($res as $v){//得到一个键是channel值为数字的一维数组    $rs[$v]++;}$arr = array();foreach($rs as $key=>$value){//将数组rs转化为键是数字,值为channel和num的二维数组    $arr[]  = array('channel'=>$key,'num'=>$value);}
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