![]() |
VOOZH | about |
To merge the duplicate value in a multidimensional array in PHP, first, create an empty array that will contain the final result. Then we iterate through each element in the array and check for its duplicity by comparing it with other elements. If duplicity is found then first merge the duplicate elements and then push it to the final array else directly push to the final array.
Below example illustrates the above approach in a more significant way:
Example 1: In this example, the duplicity is not more than two.
Output:
Array
(
[0] => Array
(
[0] => Array
(
[Roll] => 43
[name] => Geeeks
[subject] => Course-011
)
[1] => Array
(
[Rool] => 43
[name] => Geeks
[subject] => Course-011
)
)
[1] => Array
(
[Rool] => 38
[name] => Gfg
[subject] => Course-012
)
)
Example 2: In this example the duplicate field is more than two.
Output:
Array
(
[Course-011] => Array
(
[0] => Array
(
[Roll] => 43
[name] => Geeks
[subject] => Course-011
)
[1] => Array
(
[Roll] => 38
[name] => GFG
[subject] => Course-011
)
[2] => Array
(
[Roll] => 26
[name] => GeeksforGeeks
[subject] => Course-011
)
)
[Course-012] => Array
(
[0] => Array
(
[Roll] => 31
[name] => gfg
[subject] => Course-012
)
)
)
This PHP method iterates through a multidimensional array, generating unique keys based on concatenated values of specified fields ('Roll', 'name', 'subject'). It merges or adds elements based on these keys, ensuring uniqueness without relying on complex nested structures.
Example: This example shows the implementation of the above-mentioned approach.
Array ( [0] => Array ( [Roll] => 43 [name] => Geeeks [subject] => Course-011 ) [1] => Array ( [Rool] => 38 ...
This method involves using array_reduce() to iterate through the array, merging elements with the same key based on specified conditions. It efficiently consolidates duplicates into a single array structure.
Example
Array ( [Course-011] => Array ( [0] => Array ( [Roll] => 43 [name] => Geeks [subject] => Course-011 ...