"35", "Ben"=>"37", "Joe"" /> "35", "Ben"=>"37", "Joe"" /> "35", "Ben"=>"37", "Joe""/>

How to sort array having duplicate keys and values and show all keys and values respectively including duplicates from array in php?

445 Views Asked by At

I am having an issue showing all keys to their respective values while I am shorting this array in php.

$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43", "Ben"=>"56");
ksort ($age);
foreach($age as $x => $x_value) {
    echo "Key=" . $x . ", Value=" . $x_value;
}

The result I am getting is

Key=Ben, Value=56
Key=Joe, Value=43
Key=Peter, Value=35

The result should be

Key=Ben, Value=37
Key=Ben, Value=56
Key=Joe, Value=43
Key=Peter, Value=35
1

There are 1 best solutions below

5
xyz On

You cannot have multiple keys with the same "name".

It has to be possible to fetch a value by a unique key. Having the same key twice would give problems.

You can instead use a numeric array with sub-arrays to get around this:

[
 ['name' => 'Peter', 'age' => 35],
 ['name' => 'Ben', 'age' => 37],
 ['name' => 'Ben', 'age' => 56],
];

Your code adjusted:

$age = [
 ['name' => 'Peter', 'age' => 35],
 ['name' => 'Ben', 'age' => 37],
 ['name' => 'Ben', 'age' => 56],
 ['name' => 'Joe', 'age' => 43],
];

usort($age, function ($a, $b) {
    return $age['age'] - $b['age'];
});

foreach($age as $key => $person) {
    echo "Name=" . $person['name'] . ", Age=". $person['age'];
}