You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按值对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:

  1. We start with an empty $groupedResult array to store our final grouped data.
  2. The foreach loop goes through every entry in your original array: $fruitName grabs the original key (like "Ripe Mango"), and $color grabs its value (like "Yellow").
  3. 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.
  4. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:02:45