Reputation: 9804
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,
);
Upvotes: 0
Views: 52
Reputation: 1282
Simple solution, not limited to bob and alice only, handles the case of many names.
$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);
Upvotes: 1
Reputation: 940
$bobs = array_column($input, 'bob');
$alices = array_column($input, 'alice');
rsort($bobs);
rsort($alices);
$result = ['bob' => $bobs[2], 'alice' => $alices[2]];
Upvotes: 3