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

将多维数组合并至另一多维数组的子数组中

Got it, let's work through this array merging challenge together! You already nailed the first merge thanks to Philipp Maurer, but this second one needs a bit more targeted logic since we're grouping type entries and even adding new name entries where they don't exist.

First, let's recap your inputs:

Your existing master array:

$masterArray = [
    [
        'unique_codename' => 'cars',
        'sorts' => [
            ['codename' => 'cars', 'name' => 'audi'],
            ['codename' => 'cars', 'name' => 'volvo']
        ],
        'category' => 'vehicle'
    ],
    [
        'unique_codename' => 'fruit',
        'sorts' => [
            ['codename' => 'fruit', 'name' => 'banana'],
            ['codename' => 'fruit', 'name' => 'apple']
        ],
        'category' => 'food'
    ],
    [
        'unique_codename' => 'vegetables',
        'sorts' => [
            ['codename' => 'vegetables', 'name' => 'cauliflower']
        ],
        'category' => 'food'
    ]
];

The array you need to merge in:

$mergeArray = [
    ['codename' => 'fruit', 'name' => 'banana', 'type' => 'yellowbanana'],
    ['codename' => 'fruit', 'name' => 'banana', 'type' => 'brownbanana'],
    ['codename' => 'cars', 'name' => 'audi', 'type' => 'a2'],
    ['codename' => 'fruit', 'name' => 'banana', 'type' => 'greenbanana'],
    ['codename' => 'cars', 'name' => 'audi', 'type' => 'a6'],
    ['codename' => 'cars', 'name' => 'other', 'type' => 'dummytext1'],
    ['codename' => 'cars', 'name' => 'other', 'type' => 'dummytext2']
];

Your desired output:

$finalArray = [
    [
        'unique_codename' => 'cars',
        'sorts' => [
            [
                'codename' => 'cars',
                'name' => 'audi',
                'types' => [
                    ['type' => 'a2'],
                    ['type' => 'a6']
                ]
            ],
            ['codename' => 'cars', 'name' => 'volvo'],
            [
                'codename' => 'cars',
                'name' => 'other',
                'types' => [
                    ['type' => 'dummytext1'],
                    ['type' => 'dummytext2']
                ]
            ]
        ],
        'category' => 'vehicle'
    ],
    [
        'unique_codename' => 'fruit',
        'sorts' => [
            [
                'codename' => 'fruit',
                'name' => 'banana',
                'types' => [
                    ['type' => 'yellowbanana'],
                    ['type' => 'brownbanana'],
                    ['type' => 'greenbanana']
                ]
            ],
            ['codename' => 'fruit', 'name' => 'apple']
        ],
        'category' => 'food'
    ],
    [
        'unique_codename' => 'vegetables',
        'sorts' => [
            ['codename' => 'vegetables', 'name' => 'cauliflower']
        ],
        'category' => 'food'
    ]
];

Here's a PHP solution that handles all your requirements:

// First, restructure the merge array for quick lookup: key = codename|name, value = array of type entries
$mergeLookup = [];
foreach ($mergeArray as $item) {
    $key = $item['codename'] . '|' . $item['name'];
    // Remove codename and name since we don't need them in the types array
    $typeEntry = array_diff_key($item, array_flip(['codename', 'name']));
    if (!isset($mergeLookup[$key])) {
        $mergeLookup[$key] = [];
    }
    $mergeLookup[$key][] = $typeEntry;
}

// Now process the master array
foreach ($masterArray as &$group) {
    $groupCodename = $group['unique_codename'];
    // First, map existing sorts entries by their codename|name key
    $existingSorts = [];
    foreach ($group['sorts'] as &$sort) {
        $key = $sort['codename'] . '|' . $sort['name'];
        $existingSorts[$key] = &$sort;
        // Add types if they exist in the lookup
        if (isset($mergeLookup[$key])) {
            $sort['types'] = $mergeLookup[$key];
            // Remove from lookup so we don't process it again
            unset($mergeLookup[$key]);
        }
    }
    unset($sort); // Unset reference to avoid issues

    // Now handle any remaining entries in mergeLookup that belong to this group
    foreach ($mergeLookup as $key => $types) {
        list($codename, $name) = explode('|', $key);
        if ($codename === $groupCodename) {
            // Add new sort entry
            $group['sorts'][] = [
                'codename' => $codename,
                'name' => $name,
                'types' => $types
            ];
            // Remove from lookup
            unset($mergeLookup[$key]);
        }
    }
}
unset($group); // Unset reference

// $masterArray now matches your desired output
print_r($masterArray);

How this works:

  • Step 1: We create a lookup array from the merge data, using codename|name as the key. This lets us quickly find all type entries for any given codename+name pair without looping through the merge array every time.
  • Step 2: We iterate through each group in your master array, and for each existing sort entry, we check if there are matching type entries in the lookup. If so, we add the types array to the sort entry.
  • Step 3: After processing existing sorts, we check if there are any remaining entries in the lookup that belong to the current group (like the 'cars|other' entry). For these, we add a new sort entry to the group's sorts array.
  • Step 4: We unset entries from the lookup as we process them to avoid duplicate work.

This approach is efficient (roughly O(n) time complexity) and handles both updating existing entries and adding new ones exactly as you need.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:01:13