如何将数组数组转换为包含键和值的分组数组?

How to transform array of arrays into grouped arrays containing key and values?

以下是输入数组:

$input = [
    [
        'id' => 96,
        'shipping_no' => 212755-1,
        'part_no' => 'reterty',
        'description' => 'tyrfyt',
        'packaging_type' => 'PC'
    ],
    [
        'id' => 96,
        'shipping_no' => 212755-1,
        'part_no' => 'dftgtryh',
        'description' => 'dfhgfyh',
        'packaging_type' => 'PC'
    ],
    [
        'id' => 97,
        'shipping_no' => 212755-2,
        'part_no' => 'ZeoDark',
        'description' => 's%c%s%c%s',
        'packaging_type' => 'PC'
    ]
];

我想把上面的改成这样:

$output = [
    [
        'key' => 96, 
        'value' => [
            [
                'shipping_no' => 212755-1, 
                'part_no' => 'reterty', 
                'description' => 'tyrfyt', 
                'packaging_type' => 'PC'
            ], 
            [
                'shipping_no' => 212755-1, 
                'part_no' => 'dftgtryh', 
                'description' => 'dfhgfyh', 
                'packaging_type' => 'PC'
            ]
        ]
    ],
    [
        'key' => 97, 
        'value' => [
            [
                'shipping_no' => 212755-2, 
                'part_no' => 'ZeoDark', 
                'description' => 's%c%s%c%s', 
                'packaging_type' => 'PC'
            ]
        ]
    ]
];

我试过这样实现:

$result = [];
foreach ($input as $value) {
    $result[] = ['key' => $value['id'], 'value' => ['shipping_no' => $value['shipping_no'], 'part_no' => $value['part_no'], 'description' => $value['description'], 'packaging_type' => $value['packaging_type']]];
}

它没有根据公用键进行分组。请帮助我解决这个问题。

我可以看出你在制作新的子数组结构方面做得很好,但是分组应该放在第一位,因为分组是用临时键完成的,重组代码可以简化。

代码:(Demo)

$result = [];
foreach ($input as $row) {
    $id = $row['id'];
    unset($row['id']);
    if (isset($result[$id])) {
        $result[$id]['value'][] = $row;
    } else {
        $result[$id] = [
            'key' => $id,
            'value' => [$row]
        ];
    }
}
var_export(
    array_values($result)
);

解释一下过程:

  1. 在迭代输入数组时,缓存每个遇到的数据行的 id
  2. 因为您不希望在 value 子数组中保留 $row['id'],您现在可以安全地从 $row.
  3. 中删除该元素
  4. 然后检查当前 $idisset($result[$id]) 是否存在现有组。
  5. 如果该组已经存在,那么您只需将 $row 数据作为新的索引行推送到该组的 value 子数组中。
  6. 如果该组尚不存在,则它需要具有所有所需的结构 declared/populated。这意味着 key 元素已声明,并且 value 子数组必须在其第一个条目中声明。
  7. 最后,如果您不想要第一级密钥,请使用 array_values() 将其删除。