Berstos
Berstos

Reputation: 179

Filter array keys with the same values

I have the following array:

$bonusstatsarray = array(
        "bonusStat0"=> "10",
        "bonusStat1"=> "71",
        "bonusStat2"=> "40",
        "bonusStat3"=> "20",
        "bonusidbonusstat0"=> "40",
        "bonusidbonusstat1"=> "71",
    );

I want to find all array keys which have the same values. Therefore I´m using array filter():

$counts = array_count_values($bonusstatsarray);
$filtered = array_filter($bonusstatsarray, create_function('$value',
            'global $counts; return $counts[$value] > 1;'));
print_r($filtered);

And this is the output at the moment:

Array
(
    [bonusStat1] => 71
    [bonusStat2] => 40
    [bonusidbonusstat0] => 40
    [bonusidbonusstat1] => 71
)

How can I change the structure of the output array like that:

Array
( 
     [0] => Array (  [bonusStat1] => 71
                     [bonusidbonusstat1] => 71
                   )
     [1] => Array (  [bonusStat2] => 40
                     [bonusidbonusstat0] => 40
                   )
)

Upvotes: 0

Views: 84

Answers (1)

Barmar
Barmar

Reputation: 780798

Create an associative array that uses the values as the keys, and group the elements into that.

$result = [];
foreach ($bonusstatsarray as $key => $value) {
    if (isset($result[$value])) {
        $result[$value][$key] = $value;
    } else {
        $result[$value] = [$key => $value];
    }
}
$result = array_values(array_filter($result, function($list) { return count($list) > 1; })); // remove values that aren't duplicated

Upvotes: 1

Related Questions