Home  >  Article  >  php教程  >  改进的统计数组中元素出现次数的类

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

WBOY
WBOYOriginal
2016-06-06 19:37:451279browse

从别人那里改进的,原来的不能区分1和1 无 ?phpclass Statistics { private $meta = array(); private $result=array('string'=array(),'number'=array()); private $meger=array('string'=array(),'number'=array()); function __construct() { $this-meta =

从别人那里改进的,原来的不能区分1和'1'
<?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();
?>

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