搜尋

首頁  >  問答  >  主體

如何使用 UUID 值合併數組

我有以下程式碼:

<?php
$arr1 = array();
$arr1[] = ['UUID' => '123a-123a', 'name' => 'A1'];
$arr1[] = ['UUID' => '123b-123b', 'name' => 'B1'];
$arr1[] = ['UUID' => '123c-123c', 'name' => 'C1'];

$arr2 = array();
$arr2[] = ['UUID' => '123a-123a', 'name' => 'A2'];
$arr2[] = ['UUID' => '123b-123b', 'name' => 'B2'];
$arr2[] = ['UUID' => '123c-123c', 'name' => 'C2'];



$new_arr1 = array();
foreach ($arr1 as $key => $value) {
    if(isset($new_arr1[$value['UUID']])){
        $new_arr1[$value['UUID']] += ['name_a' => $value['name']];
    }else{
        $new_arr1[$value['UUID']] = ['name_a' => $value['name']];
    }
    
}
$new_arr2 = array();
foreach ($arr2 as $key => $value) {
    if(isset($new_arr2[$value['UUID']])){
        $new_arr2[$value['UUID']] += ['name_1' => $value['name']];
    }else{
        $new_arr2[$value['UUID']] = ['name_2' => $value['name']];
    }
    
}
 $final_array = array_combine($new_arr1, $new_arr2);
var_dump($final_array);

這給了我以下錯誤:

Warning: Array to string conversion in /home/user/scripts/code.php on line 32

片段:

https://sandbox.onlinephpfunctions.com/c/cf5fd

我想使用 UUID 作為陣列 ID。

這是預期的輸出:

Array
(
    [123a-123a] => Array
        (
            [name_1] => A1
            [name_2] => A2
        )

    [123b-123b] => Array
        (
            [name_1] => B1
            [name_2] => B2
        )

    [123c-123c] => Array
        (
            [name_1] => C1
            [name_2] => C2
        )
)

P粉633075725P粉633075725230 天前366

全部回覆(2)我來回復

  • P粉340980243

    P粉3409802432024-03-30 11:53:32

    不需要array_combine也不需要中間數組,只需從已有的陣列中建構新數組即可:

    $arr1 = array();
    $arr1[] = ['UUID' => '123a-123a', 'name' => 'A1'];
    $arr1[] = ['UUID' => '123b-123b', 'name' => 'B1'];
    $arr1[] = ['UUID' => '123c-123c', 'name' => 'C1'];
    
    $arr2 = array();
    $arr2[] = ['UUID' => '123a-123a', 'name' => 'A2'];
    $arr2[] = ['UUID' => '123b-123b', 'name' => 'B2'];
    $arr2[] = ['UUID' => '123c-123c', 'name' => 'C2'];
    
    
    $final_array = [];
    foreach( array_merge($arr1, $arr2) as $entry ){
    
        if( empty( $final_array[$entry['UUID']] ) )
            $final_array[$entry['UUID']] = ['name_1' => $entry['name']];
        else
            $final_array[$entry['UUID']][ 'name_' . (count( $final_array[$entry['UUID']] ) + 1) ] = $entry['name'];
    }
    
    print_r($final_array);

    回覆
    0
  • P粉769413355

    P粉7694133552024-03-30 09:37:41

    您需要使用array_merge_recursive而不是使用array_combine,因為它是多維的

    片段: https://sandbox.onlinephpfunctions.com/c/eae35

    #參考:

    回覆
    0
  • 取消回覆