为什么这个模式函数返回null?

时间:2017-03-31 15:43:28

标签: php

在下面的function中,当我致电

mmmr(array(1,2,3,3,4,3), 'mode', 'ceil'); // null

它返回null。如果我没有设置第三个($round)参数,那么工作正常。

mmmr(array(1,2,3,3,4,3), 'mode'); // 3

我错过了什么?咖啡吗?

function mmmr( array $array, $output = 'mean', $round = false ) {

        switch( $output ) {

                case 'mode':

                if( $round == "ceil" ) {
                    foreach( $array as $key => $value ) {
                        $array[$key] = ceil( $value );
                    }
                } elseif( $round == "floor" ) {
                    foreach( $array as $key => $value ) {
                        $array[$key] = floor( $value );
                    }
                } elseif( $round == "normal" ) {
                    foreach( $array as $key => $value ) {
                        $array[$key] = round( $value );
                    }
                }

                $v = array_count_values( $array );
                arsort( $v );
                foreach( $v as $k => $v ) {
                    $total = $k;
                    break;
                }
                break;


        }

        return $total;

    }

1 个答案:

答案 0 :(得分:2)

array_count_values()只能计算STRINGINTEGER值。 ceil()floor()round()返回浮点数。将其投放到int会解决您的问题:

<?php

function mmmr( array $array, $output = 'mean', $round = false ) {

    switch( $output ) {

            case 'mode':

            if( $round == "ceil" ) {
                foreach( $array as $key => $value ) {
                    $array[$key] = (int) ceil( $value ); // (int)
                }
            } elseif( $round == "floor" ) {
                foreach( $array as $key => $value ) {
                    $array[$key] = (int) floor( $value ); // (int)
                }
            } elseif( $round == "normal" ) {
                foreach( $array as $key => $value ) {
                    $array[$key] = (int) round( $value ); // (int)
                }
            }

            $v = array_count_values( $array );
            arsort( $v );
            foreach( $v as $k => $v ) {
                $total = $k;
                break;
            }
            break;


    }

    return $total;

}

echo mmmr(array(1,2,3,3,4,3), 'mode', 'ceil'); // Returns 3