duanfang7757
duanfang7757
2019-04-14 14:07
浏览 34
已采纳

如何从MySQL查询计算关联数组的中值?

I get an associative array of values using fetchAll(PDO::FETCH_ASSOC) and I get the following array:

Array ( [0] => Array ( [value] => 12.00000 ) [1] => Array ( [value] => 12.00000 ) [2] => Array ( [value] => 1001.00000 ) [3] => Array ( [value] => 1001.00000 ) [4] => Array ( [value] => 1.00000 ) [5] => Array ( [value] => 101.00000 ) [6] => Array ( [value] => 155.00000 ) [7] => Array ( [value] => 100.00000 ) [8] => Array ( [value] => 100.14300 ) [9] => Array ( [value] => 10123.12000 ) ) 

How to get the median value? I can't just use arsort and get the middle value because it's an array within array and I get stuck

How to do it?

Edit: I tried using array_column($array, 'value'), and now it extracted the value, then I used asort and got the following output:

Array ( [4] => 1.00000 [0] => 12.00000 [1] => 12.00000 [7] => 100.00000 [8] => 100.14300 [5] => 101.00000 [6] => 155.00000 [2] => 1001.00000 [3] => 1001.00000 [9] => 10123.12000 ) 

So the problem is that asort does sort the array, but only for the output, but it's not actually sorting it, so for example $array[0] is not the minimum value (1.0000) in my case, but it's actually the original value 12.00000.

What am I missing?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douhunkuang8955
    douhunkuang8955 2019-04-14 14:11
    已采纳

    Extract value fields from your array with:

    $values = array_column($array, 'value');
    // now `sort` and do what you need
    arsort($values);
    

    arsort sorts array. If you open a manual you will see that arsort

    sorts an array such that array indices maintain their correlation with the array elements they are associated with.

    So, obviously you need another function, I suppose just rsort.

    点赞 评论

相关推荐