下面是我的数组。我想找到平均值和模式。
如果值是数字,则平均函数运行并找到平均值并将结果放在空空间中,如果值是字符串类型,则找到模式(重复次数最多的值)并将该值放在空空间中...
如何使两个函数来查找平均值和模式,以及如何判断值是数字和字符串,然后应用函数并填充空格?
Array
[1] => Array
(
[1] => 4
[2] => 2
[3] => 3
[4] =>
)
[2] => Array
(
[1] => one
[2] => two
[3] => two
[4] =>
)
[3] => Array
(
[1] => 8
[2] =>
[3] => 8
[4] => 5
)
}
您将需要使用以下语句和函数:
-
foreach
:迭代元素 - empty():检测空插槽
- is_numeric():了解值是否为数字
-
&
:不是绝对必要的,但此前缀使您可以更轻松地在迭代数组元素时修改数组。
下面是一个用均值和模式填充空白的函数:
function meanAndMode(&$data) {
// repeat for each row in the data
foreach($data as &$row) {
$sum = 0;
$mode = "";
$numbers = 0;
$numeric = true;
$emptySlots = [];
foreach($row as $index => &$value) {
if (empty($value)) {
// remember where the empty slot(s) are, using "&"
$emptySlots[] = &$value;
} else {
// all entries must be numeric to get the average,
// otherwise they will be used as strings for get the mode.
$numeric = $numeric && is_numeric($value);
if ($numeric) {
// numeric: add up and count for
// allowing mean to be calculated later
$sum += $value;
$numbers++;
}
// for numeric and non-numeric: keep count per string
$count[$value] = empty($count[$value]) ? 1
: $count[$value] + 1;
// keep track of highest recurrence count
if (!$mode || $count[$value] > $count[$mode]) {
$mode = $value;
}
}
}
// Put result in empty slot(s). In case of numeric input,
// the average needs to be calculated still:
$result = $numeric ? $sum / $numbers : $mode;
foreach ($emptySlots as &$emptySlot) {
$emptySlot = $result;
}
// avoid that the same slot is used in a next iteration that might
// treat a row without an empty slot.
unset($emptySlots);
}
}
以下是您的称呼:
// test data
$data = array(
array(4, 2, 3, null),
array("one","two","two", null),
array(8, null, 8, 5)
);
// apply function to fill in the blanks
meanAndMode($data);
// show result
var_export ($data);
输出为:
array (
0 =>
array (
0 => 4,
1 => 2,
2 => 3,
3 => 3,
),
1 =>
array (
0 => 'one',
1 => 'two',
2 => 'two',
3 => 'two',
),
2 =>
array (
0 => 8,
1 => 7,
2 => 8,
3 => 5,
),
)
请注意,此函数始终计算模式,但如果最后发现所有元素都是数字,它将用平均值填充间隙,并忽略模式。这样,当混合使用数字和非数字数据时,该函数将很好地工作。在这种情况下,所有内容都将被解释为非数字。
如果有多个空槽,则所有空槽都将收到结果值。