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

PHP关联数组重构优化问询:合并重复键值/保留单值

Better Solutions for Restructuring Your PHP Array

Your existing solution gets the job done, but we can refine it to be more concise, readable, and robust. Here are two optimized approaches tailored to your needs:

Approach 1: Functional Grouping + Transformation (Most Readable)

This method breaks the task into two clear, intuitive steps—first grouping all values by their key, then collapsing single-value groups into scalars. It’s easy to follow and maintain:

$input = [ 
    ['key'=>'x', 'value'=>'a'], 
    ['key'=>'x', 'value'=>'b'], 
    ['key'=>'x', 'value'=>'c'], 
    ['key'=>'y', 'value'=>'d'], 
    ['key'=>'y', 'value'=>'e'], 
    ['key'=>'z', 'value'=>'f'], 
    ['key'=>'m', 'value'=>'n'], 
];

// Step 1: Group all values by their 'key'
$grouped = array_reduce($input, function($carry, $item) {
    $carry[$item['key']][] = $item['value'];
    return $carry;
}, []);

// Step 2: Convert single-element arrays to scalars
$output = array_map(function($values) {
    return count($values) === 1 ? $values[0] : $values;
}, $grouped);

print_r($output);

Key Benefits:

  • Clear Intent: The two separate steps make the code’s purpose obvious at a glance, even to new readers.
  • Robustness: Avoids issues with empty values (like '' or 0) that the original empty() check might mishandle.
  • Conciseness: Leverages PHP’s built-in array functions to cut down on boilerplate code.

Approach 2: Optimized Foreach Loop (Slightly More Efficient)

If you prefer a single-loop approach, this streamlined version fixes edge cases and simplifies the conditional logic:

$output = [];
foreach ($input as $item) {
    $key = $item['key'];
    $value = $item['value'];
    
    if (!isset($output[$key])) {
        $output[$key] = $value;
    } else {
        // Convert scalar to array if needed, then append
        if (!is_array($output[$key])) {
            $output[$key] = [$output[$key]];
        }
        $output[$key][] = $value;
    }
}

print_r($output);

Improvements Over Your Original Code:

  • Uses isset() instead of empty(), which correctly handles "falsy" but valid values like empty strings or zero.
  • Removes redundant continue statements and combines checks for cleaner, more scannable logic.
  • Reduces cognitive load by simplifying the flow of conditionals.

Both approaches will generate exactly the output you’re looking for, with better readability and reliability than your initial solution.

内容的提问来源于stack exchange,提问作者Abhay Maurya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:12:52