当前位置 : 主页 > 网络编程 > PHP >

改进的统计数组中元素出现次数的类

来源:互联网 收集:自由互联 发布时间:2021-07-03
?phpclass Statistics { private $meta = array(); private $result=array('string'=array(),'number'=array()); private $meger=array('string'=array(),'number'=array()); function __construct() { $this-meta = func_get_args(); } public function show
 
<?php
class Statistics {
  
    private $meta = array();
    private $result=array('string'=>array(),'number'=>array());
    private $meger=array('string'=>array(),'number'=>array());
  
    function __construct() {
        $this->meta = func_get_args();
    }
  
    public function show(){
        $this->count_elems($this->meta);
        var_dump($this->result);
    }
  
    private function count_elems($array) {
        //遍历数组
        foreach ($array as $value) {
            //如果$value不是数组,就判断其出现次数,否则调用本身再次遍历
            if(!is_array($value)) {
                //若变量作为数组下标,且该变量值可以转换成数字,如数字字符串,php会自动将其转化成数字,所有要分类保存
               if(is_string($value)){
                   if (!in_array($value, $this->meger['string'])) {
                       $this->meger['string'][] = $value;
                       $this->result['string'][$value] = 1;
                   } elseif (in_array($value, $this->meger['string'])) {
                       $this->result['string'][$value]++;
                   }
               }else{
                   if (!in_array($value, $this->meger['number'])) {
                       $this->meger['number'][] = $value;
                       $this->result['number'][$value] = 1;
                   } elseif (in_array($value, $this->meger['number'])) {
                       $this->result['number'][$value]++;
                   }
               }
            }else{
                $this->count_elems($value);
            }
        }
    }
}
  
$arr1 = array('a', 'b', array(1,2,3,4,'dd','fdf','nid','innid','iii','ieir'));
$arr2 = array('d', 'de', 'ef','2','5','8');
$arr3 = array('a', 'ef', 'r', 'q');
$arr4 = array('b', 'de', 'q', 'z');
$arr5 = array('1', 'de', 'q', '3r');
$arr6 = array(1, 1, 2, 'mn', '0y');
$arr7 = array(1, 'v2d', 'mn', '0y');
$s = new Statistics($arr1, $arr2, $arr3, $arr4, $arr5, $arr6, $arr7);
$s->show();
?>

网友评论