如何通过code键合并拆分的多属性产品数组?
Merge Array Entries by Unique
code Field Hey, no problem—here's a clean, array-level solution to combine your duplicate product entries into single objects with all their attributes, no SQL changes needed.
Original Input Array
$originalArray = [ ['code' => '123', 'name' => 'box', 'stock' => '2.00', 'price' => '10.00', 'color' => 'brown'], ['code' => '123', 'name' => 'box', 'stock' => '2.00', 'price' => '10.00', 'size' => 'L'], ['code' => '1234', 'name' => 'box', 'stock' => '3.00', 'price' => '11.00', 'color' => 'brown'], ['code' => '1234', 'name' => 'box', 'stock' => '3.00', 'price' => '11.00', 'size' => 'XL'], ['code' => '12345', 'name' => 'box', 'stock' => '4.00', 'price' => '12.00', 'size' => 'XL'], ['code' => '12345', 'name' => 'box', 'stock' => '4.00', 'price' => '12.00', 'color' => 'gray'], ];
The Solution Code
We'll use the code field as a unique key to group and merge entries:
$mergedArray = []; foreach ($originalArray as $item) { $productCode = $item['code']; // Merge current item into the existing product entry, or create a new one if (isset($mergedArray[$productCode])) { $mergedArray[$productCode] = array_merge($mergedArray[$productCode], $item); } else { $mergedArray[$productCode] = $item; } } // Optional: Convert from associative array to sequential indexed array $mergedArray = array_values($mergedArray); // Output the result print_r($mergedArray);
How It Works
- Group by
code: We use the product's uniquecodeas the key in a temporary associative array. This ensures all entries for the same product are grouped together. - Merge Attributes: For each entry, we either create a new entry in the temporary array or merge the current entry's attributes into the existing one. Since your duplicate entries only differ by
color/size(all other fields are identical),array_merge()will safely combine them without overwriting critical data. - Reset Indexes: The
array_values()call converts the associative array (keyed bycode) back to a sequential indexed array, matching your desired output format.
Expected Output
Running the code will give you exactly what you're looking for:
Array ( [0] => Array ( [code] => 123 [name] => box [stock] => 2.00 [price] => 10.00 [color] => brown [size] => L ) [1] => Array ( [code] => 1234 [name] => box [stock] => 3.00 [price] => 11.00 [color] => brown [size] => XL ) [2] => Array ( [code] => 12345 [name] => box [stock] => 4.00 [price] => 12.00 [size] => XL [color] => gray ) )
This approach is flexible too—if you ever have more than two entries per product (e.g., additional attributes stored in separate tables), it will still merge them all into a single product array as long as the code is consistent.
内容的提问来源于stack exchange,提问作者kopz
相关产品推荐
相关产品推荐

