0

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
    Maybe see https://stackoverflow.com/questions/1291152/simple-way-to-calculate-median-with-mysql ... assuming you don't need the other values later – user3783243 Apr 14 '19 at 14:14
  • How are you using the array? The keys are still maintained so `0` always has the same value. – user3783243 Apr 14 '19 at 14:29

1 Answers1

0

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.

u_mulder
  • 51,564
  • 5
  • 39
  • 54
  • I just tried it, but it doesn't really sort the array, I added the example in the original post – Stackerovich Apr 14 '19 at 14:25
  • `arsort` __sorts array__. Obviously, you do something wrong. – u_mulder Apr 14 '19 at 14:28
  • Look at the original associative array, it was an array containing arrays, and you can see it looked like `( [0] => Array ( [value] => 12.00000 )` so maybe `array_column` did filter out the `value` but left the original `[0]`? You can see that in the output `arsort` did sort the array but left the original numbers, I need to filter them out as well? – Stackerovich Apr 14 '19 at 14:32