合併具有共享列值的關聯數組數組
P粉966979765
P粉966979765 2023-11-09 08:47:41
0
2
517

我想根據公共列值合併兩個陣列。這是我的 2 個陣列:

$array1 = [
    [
        "total_process_per_category" => "6",
        "category_id" => "1"
    ],
    [
        "total_process_per_category" => "2",
        "category_id" => "2"
    ]
];

$array2 = [
    [
        "total_pinned_per_category" => "16",
        "category_id" => "1"
    ],
    [
        "total_pinned_per_category" => "4",
        "category_id" => "2"
    ]
];

我想合併這些陣列以獲得:

array (
  0 => 
  array (
    'total_process_per_category' => '6',
    'total_pinned_per_category' => '16',
    'category_id' => '1',
  ),
  1 => 
  array (
    'total_process_per_category' => '2',
    'total_pinned_per_category' => '4',
    'category_id' => '2',
  ),
)

如您所見,這兩個陣列具有相同的鍵 ['category_id'] 和相同的值。

我想要得到一個結果,其中 ['total_process_per_category'] 和 ['total_pinned_per_category'] 根據它們的 ['category_id'] 值一起放置在同一數組上。

我使用嵌套的 foreach 得到了這個,但它看起來很醜。請告訴我更好的方法。

P粉966979765
P粉966979765

全部回覆(2)
P粉366946380

這可以在沒有「醜陋的巢狀 foreach」的情況下完成。在迭代之前合併兩個數組,按category_id 值進行分組。循環結束後,使用 array_values() 清除暫時的一級鍵。

程式碼:(示範) (array_reduce() 版本)

$result = [];
foreach (array_merge($array1, $array2) as $row) {
    $result[$row['category_id']] = ($result[$row['category_id']] ?? []) + $row;
}
var_export(array_values($result));

輸出:

array (
  0 => 
  array (
    'total_process_per_category' => '6',
    'category_id' => '1',
    'total_pinned_per_category' => '16',
  ),
  1 => 
  array (
    'total_process_per_category' => '2',
    'category_id' => '2',
    'total_pinned_per_category' => '4',
  ),
)
P粉071743732

你可以嘗試array_reduce

$someVariable = 'someValue';
$result = array_reduce(array_merge($array1, $array2), function ($carry, $item) use ($someVariable) {
    if (isset($carry[$item['category_id']])) {
        $carry[$item['category_id']] = array_merge($carry[$item['category_id']], $item);
    } else {
        $carry[$item['category_id']] = $item;
    }
    return $carry;
}, array());

var_dump($result);
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!