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

如何从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 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?