I have the following scenario made of arrays with numeric keys.
I need to have an array which stores all the values in the arrays grouped by numeric key and without duplicates.
I cannot make them strings as they are IDs and need to stay numeric.
Starting point:
Array
(
[77] => Array
(
[0] => Bold Condensed
[1] => Bold Condensed 2
[2] => Bold Condensed 3
)
)
Array
(
[77] => Array
(
[0] => Bold Condensed
)
[136] => Array
(
[0] => Regular
)
)
Array
(
[77] => Array
(
[0] => Bold Condensed (1, 2, 3)
)
[168] => Array
(
[0] => Regular
[1] => Bold
)
)
Expected output:
Array
(
[77] => Array
(
[0] => Bold Condensed
[1] => Bold Condensed 2
[2] => Bold Condensed 3
[3] => Bold Condensed (1 ,2 ,3)
)
[136] => Array
(
[0] => Regular
)
[168] => Array
(
[0] => Regular
[1] => Bold
)
)
Tried array_merge and array_merge_recursive:
$megaArray = [];
foreach( $arrays as $key => $value) {
if(array_key_exists($key, $arrays)){
$megaArray[$key] = array_merge_recursive($value);
}
}
What I’m getting with both array_merge and array_merge_recursive:
Array
(
[77] => Array
(
[0] => Bold Condensed (1, 2, 3)
)
[136] => Array
(
[0] => Regular
)
[168] => Array
(
[0] => Regular
[1] => Bold
)
)
Both array_merge and array_merge_recursive seem to store the latest value for each key.
5
Answers
I think you just need a combination of
array_merge
andarray_unique
(since I note you don’t have duplicates in your leaf arrays):Based on your expected output, it seems you need to check key and values at the same time. I write a code that create exact output array like your sample. No need to say that you can use function to simplify the whole process but for understanding the principle of situation, I repeat foreach each time.
array_merge_recursive
is not required since there is only 1 level for each ID and yourarray_key_exists
will always be true since you are getting the same key from foreach and checking on the same array.You can straightaway get values based on
id
(which is77
etc in your case) and keep merging values. You can laterarray_unique
them only once for efficiency and get only unique values for each id.Live Demo
here is the code
The mergeArrays function will accepts multiple arrays as arguments and merges them into a single result array. It loop through each array, combining values for each key while removing duplicates