简体   繁体   中英

php unique multidimensional array by keeping entry with the highes value from one dimension?

I have another array unique question in the endless list of questions about them. I can imagine this problem is quite simple to solve but I simply do not come on it. Just because there are so many questions on this subject i wasn't able to find anything useful in this case.

the array:

Array
(
  [0] => Array
    (
      [0] => blabla values
      [1] => 91.181818181818
    )
  [1] => Array
    (
      [0] => blabla same values
      [1] => 95.333333333333
    )
  [2] => Array
    (
      [0] => blabla other values
      [1] => 86
    )
  [3] => Array
    (
      [0] => blabla other values
      [1] => 92.5
    )
  [4] => Array
    (
      [0] => blabla same values
      [1] => 88.5
    )
)

I want to unique the array by the first array dimension and only keep the entry with the highest value from the second.

Maybe in MYSQL this would be no big deal but at the moment i am not able to implement something like that in php.

desired output array would be:

Array
(
  [0] => Array
    (
      [0] => blabla values
      [1] => 91.181818181818
    )
  [1] => Array
    (
      [0] => blabla same values
      [1] => 95.333333333333
    )
  [2] => Array
    (
      [0] => blabla other values
      [1] => 92.5
    )
)

Has anyone a clever idea?

<?php
$list = array(
    array('blabla values',91.181818181818),
    array('blabla same values', 95.333333333333),
    array('blabla other values', 86),
    array('blabla other values', 92),
    array('blabla same values', 88.5),
);
$result = array();
foreach ($list as $item)
{
    $key = $item[0];
    $value = $item[1];
    if (!isset($result[$key]) || $result[$key][1] < $value)
    {
        $result[$key] = $item;
    }
}
$result = array_values($result);
print_r($result);

the output:

Array
(
    [0] => Array
        (
            [0] => blabla values
            [1] => 91.1818181818
        )

    [1] => Array
        (
            [0] => blabla same values
            [1] => 95.3333333333
        )

    [2] => Array
        (
            [0] => blabla other values
            [1] => 92
        )

)
usort($arr, function ($a, $b){
    return $a[1] - $b[1];
});
$out = array();
foreach ($arr as $key => $value){
    $out[$value[0]] = $value[1];
}
$arr = array_map(NULL, array_keys($out), $out);

Output:

 Array
(
    [0] => Array
        (
            [0] => blabla same values
            [1] => 95.333333333333
        )

    [1] => Array
        (
            [0] => blabla other values
            [1] => 86
        )

    [2] => Array
        (
            [0] => blabla values
            [1] => 91.181818181818
        )

)

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