在下面的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;
}
答案 0 :(得分:2)
array_count_values()
只能计算STRING
和INTEGER
值。 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