PHP从数组中查找中值并返回键和值?

时间:2017-09-30 15:42:39

标签: php arrays

我有一系列频道,到目前为止我知道如何返回这样的最小值和最大值:

// clear from any empty channels
$channels = array_filter($scan['channels']);

// get min/max values
$min = array_keys($channels, min($channels));
$max = array_keys($channels, max($channels));
// this returns the channel name wich is what I need

到目前为止,我想获得中位数键(通道)名称,我该如何实现?

// this is the array of channels
Array
(
    [chann_1] => 155.755
    [chann_2] => 154.61
    [chann_3] => 156.719
    [chann_4] => 156.727
    [chann_5] => 155.797
    [chann_6] => 157.615
    [chann_7] => 154.257
    [chann_8] => 151.724
    [chann_9] => 156.549
    [chann_10] => 156.594
    [chann_11] => 157.56
    [chann_12] => 156.405
)

2 个答案:

答案 0 :(得分:2)

试试这个:

对数组进行排序 获取数组键 然后,array_keys的一半计数是中值。 (为了以防万一,我加了一轮)。

$arr = Array(
"chann_1" => 155.755,
"chann_2" => 154.61,
"chann_3" => 156.719,
"chann_4" => 156.727,
"chann_5" => 155.797,
"chann_6" => 157.615,
"chann_7" => 154.257,
"chann_8" => 151.724,
"chann_9" => 156.549,
"chann_10" => 156.594,
"chann_11" => 157.56,
"chann_12" => 156.405);

Arsort($arr);
//Var_dump($arr);
$keys = array_keys($arr);
Echo $keys[round(count($keys)/2)];

https://3v4l.org/ER3d4

答案 1 :(得分:0)

使用array_search()$max_key=array_search($max,$yourArray);$min_key=array_search($min,$yourArray);$median=$max_key+$min_key/2;当然取决于您的阵列大小。

尝试$median=array_search($max+$min/2,$yourArra);