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
''or0) that the originalempty()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 ofempty(), which correctly handles "falsy" but valid values like empty strings or zero. - Removes redundant
continuestatements 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
相关产品推荐
相关产品推荐

