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 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用