wawanopoulos wawanopoulos - 11 days ago 6
PHP Question

Get third biggest value in multidimensional array php

I have an input array containing n entries representing hours. (until 24). For each hour, there is an array containing people (bob and alice) with a value. I would like to get the third biggest hour of each people in ouput. (See output example).

Is there an easy way to to that in PHP ?

$input = array(
'0' => array(
'bob' => 8
'alice' => 19
),
'1' => array(
'bob' => 2
'alice' => 1
),
'2' => array(
'bob' => 9
'alice' => 0
),
'n' => array(
'bob' => 6
'alice' => 7
),
...
);


I would like to get this output:

$output = array(
'bob' => 6,
'alice' => 1,
);

Answer
$results = [];

foreach($input as $array)
    foreach($array as $name => $hours)
        $results[$name][] = $hours;

$results = array_map(function($v){
    natsort($v);
    $v = array_values($v);
    return $v[count($v) - 3];
}, $results);
Comments