I have the following code :
<?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);
Which give me the following error :
Warning: Array to string conversion in /home/user/scripts/code.php on line 32
Snippet :
https://sandbox.onlinephpfunctions.com/c/cf5fd
I want to use the UUID as an array id.
here is the expected output :
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
)
)
My Answer:
To merge the arrays using the UUID value as the array id, you can modify your code as follows:
php
$arr1 = array();
$arr1['123a-123a'] = ['name' => 'A1'];
$arr1['123b-123b'] = ['name' => 'B1'];
$arr1['123c-123c'] = ['name' => 'C1'];
$arr2 = array();
$arr2['123a-123a'] = ['name' => 'A2'];
$arr2['123b-123b'] = ['name' => 'B2'];
$arr2['123c-123c'] = ['name' => 'C2'];
$final_array = array();
foreach ($arr1 as $key => $value) {
$final_array[$key] = array_merge($value, $arr2[$key]);
}
var_dump($final_array);
?>
This code will give you the expected output where the UUID values are used as array keys and the names from both arrays are merged into a single array for each UUID.
Rate this post
4 of 5 based on 6546 votesComments