PHP合并数组生成3组分组结构时的键覆盖问题求助
Got it, let's break down why your current code is causing key overwrites and fix it to get the 3 grouped objects you need.
The Root Problem
Your original code loops through all 33 items in $ArrayObj and assigns values directly to $Array2[$Array1[$key]]. Since every 11 items share the same left_side_data values (your keys), each subsequent duplicate key overwrites the previous value. That's why you end up with only 1 set of 11 key-value pairs instead of 3 separate groups.
Solution: Group First, Then Build Key-Value Pairs
The fix is simple: split your original 33-item array into 3 groups of 11 first, then build a key-value array for each group. This way, duplicate keys are contained within their own group and won't overwrite each other across groups.
Here's the revised code:
// Your original 33-object array $ArrayObj = [...]; // Define the size of each group (11 items per group) $groupSize = 11; $Array2 = []; // Split the original array into 3 groups of 11 items each $groupedObjects = array_chunk($ArrayObj, $groupSize); // Loop through each group to build the key-value pairs foreach ($groupedObjects as $group) { // Use array_column to extract keys and values, then combine them $keys = array_column($group, 'left_side_data'); $values = array_column($group, 'data'); $Array2[] = array_combine($keys, $values); } return $Array2;
What This Does
array_chunk($ArrayObj, 11): Takes your 33-item array and splits it into 3 sub-arrays, each containing exactly 11 objects.array_column: Extracts allleft_side_datavalues (to use as keys) and alldatavalues (to use as values) from each group.array_combine: Merges the extracted keys and values into a single associative array for each group.$Array2[] = ...: Adds each group's associative array to the final output, resulting in an array of 3 objects (each with 11 key-value pairs).
Alternative: Manual Loop (If You Prefer)
If you want to avoid array_column and array_combine for more explicit control, you can use nested loops:
$ArrayObj = [...]; $groupSize = 11; $Array2 = []; $groupedObjects = array_chunk($ArrayObj, $groupSize); foreach ($groupedObjects as $group) { $groupData = []; foreach ($group as $item) { $groupData[$item['left_side_data']] = $item['data']; } $Array2[] = $groupData; } return $Array2;
Both approaches will give you the exact 3-group structure you're looking for, with no key overwrites.
内容的提问来源于stack exchange,提问作者Murlidhar Fichadia

