如何按值对PHP关联数组分组并保留原键为组内元素?
Solution to Group PHP Associative Array by Value
Hey there! Let's fix up that groupByColor function to get the grouped array you're expecting. The core idea is to iterate through your original array, and for each fruit-color pair, organize the fruits under their corresponding color keys in a new array.
Here's the modified working code:
$associativeArray = array("Ripe Mango"=>"Yellow", "Strawberry"=>"Red", "Lemon"=>"Yellow"); function groupByColor($groupedArray) { // Initialize an empty array to hold our grouped results $groupedResult = []; // Loop through each key-value pair in the input array foreach ($groupedArray as $fruitName => $color) { // Check if this color already exists as a key in our result if (isset($groupedResult[$color])) { // If it does, add the fruit name to the existing color group $groupedResult[$color][] = $fruitName; } else { // If not, create a new group for this color with the current fruit $groupedResult[$color] = [$fruitName]; } } return $groupedResult; } // Test the function print_r(groupByColor($associativeArray));
How this works:
- We start with an empty
$groupedResultarray to store our final grouped data. - The
foreachloop goes through every entry in your original array:$fruitNamegrabs the original key (like "Ripe Mango"), and$colorgrabs its value (like "Yellow"). - For each pair, we check if the color is already a key in
$groupedResult:- If yes: We append the fruit name to the existing array under that color.
- If no: We create a new entry where the key is the color, and the value is an array containing the current fruit name.
- Finally, we return the fully grouped array.
The output you'll get:
Array ( [Yellow] => Array ( [0] => Ripe Mango [1] => Lemon ) [Red] => Array ( [0] => Strawberry ) )
Alternative concise approach (using array_reduce):
If you prefer a more functional programming style, you can use array_reduce instead of a loop:
function groupByColor($groupedArray) { return array_reduce(array_keys($groupedArray), function($acc, $fruit) use ($groupedArray) { $color = $groupedArray[$fruit]; $acc[$color][] = $fruit; return $acc; }, []); }
This achieves the same result, though the foreach version is often easier to read and debug for most developers.
内容的提问来源于stack exchange,提问作者Jan Ariel San Jose
相关产品推荐
相关产品推荐

