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

PHP合并数组生成3组分组结构时的键覆盖问题求助

Fixing the Key Overwriting Issue for Grouped Array Output

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

  1. array_chunk($ArrayObj, 11): Takes your 33-item array and splits it into 3 sub-arrays, each containing exactly 11 objects.
  2. array_column: Extracts all left_side_data values (to use as keys) and all data values (to use as values) from each group.
  3. array_combine: Merges the extracted keys and values into a single associative array for each group.
  4. $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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:23:49