简体   繁体   中英

Get the maximum $key value from array with keys ($key -> $value) for every unique $value in php

i have an $array with keys like this:

Array
(
    [1] => 462
    [2] => 462
    [3] => 462
    [4] => 462
    [5] => 19
    [6] => 19
    [7] => 19
    [8] => 462
)

where 1,2,3,4,5,6,7,8 are keys and 462,462,462,462,19,19,19,462 are values. I want to get the maximum key for every unique value, so, the result must be an array like:

Array
    (
        [7] => 19
        [8] => 462
    )

How can i get maximum $key for all the unique $values? I know i can get the maximum key and maximum value with:

foreach ($array as $key => $value) {
                $keys[] = $key;
                $values[] = $value;
}
echo "max key is - ".max($keys);
echo "max value is - ".max($values);

But it is not exactly what i need. So what can be a solition?

Just using array_flip() will first reduce all of the duplicates to 1 element (arrays can't have more than one key with the same value), so...

$a = [1=>462,462,462,462,19,19,19,462];
print_r(array_flip($a));

gives

Array
(
    [462] => 8
    [19] => 7
)

You could use array_flip() again to swap the keys/values...

print_r(array_flip(array_flip($a)));

gives...

Array
(
    [8] => 462
    [7] => 19
)

Make an array $maxis takes keys of the unique value and store them as elements.

$array = [1=>462, 2=>462, 3=>462, 4=>462, 5=>19, 6=>19, 7=>19, 8=>462];
$maxis = [];
foreach ($array as $key => $value) {
    $maxis[$value][] = $key;
}
/*
462: [1,2,3,4,8]
19: [5,6,7]
*/

Loops over $maxis and store maximum of $arr_keys as key, and $key as its value.

$res = [];
foreach ($maxis as $key=> $arr_keys) {
    $res[max($arr_keys)] = $key;
}
print_r($res);

Prints:

Array
(
    [8] => 462
    [7] => 19
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM