<?php
// groupA:
// James:
// gpa: 3
// age: 13
// Charles:
// gpa: 4
// age: 15
// John:
// gpa: 2
// age: 17
$groupA = [
'James' => [
'gpa' => 3,
'age' => 13
],
'Charles' => [
'gpa' => 4,
'age' => 15
],
'John' => [
'gpa' => 2,
'age' => 17
]
];
/**
* @throws \InvalidArgumentException
*/
function getPlace(string $for, string $compareValueKey, array $haystack, int $flags = SORT_REGULAR): int
{
if(empty($haystack) || !isset($haystack[$for]))
{
throw new \InvalidArgumentException("empty haystack array given (or key '$for') was not found");
}
$sort = array_map(fn(array $el) => $el[$compareValueKey], $haystack);
arsort($sort, $flags);
$place = array_search($for, $places = array_keys($sort), true);
if(!is_int($place))
{
throw new \RuntimeException("could not locate position for key '$for' in given array: " . trim(implode(', ', $places)));
}
return $place + 1;
}
$persons = array_keys($groupA);
foreach($persons as $person)
{
echo $person . ': ' . getPlace($person, 'age', $groupA) . PHP_EOL;
}
preferences:
30 ms | 402 KiB | 5 Q