欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

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

程序员文章站 2024-02-15 18:33:34
...

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