Open In App

How to merge the duplicate value in multidimensional array in PHP ?

Last Updated : 11 Feb, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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 illustrate the above approach in a more significant way:
Example 1: In this example the duplicity is not more than two. 
 

PHP




<?php
$arr = array(
    array('Roll'=>43, 'name'=>'Geeeks', 'subject'=>'Course-011'),
    array('Rool'=>38, 'name'=>'Gfg', 'subject'=>'Course-012'),
    array('Rool'=>43, 'name'=>'Geeks', 'subject'=>'Course-011')
);
     
 
// Create an empty array
$myarray = array();
     
// It returns the keys of the array
$keys = array_keys($arr);
 
// Iterating through the multidimensional array
for($i = 0; $i < count($arr); $i++) {
 
    $keys = array_keys($arr);
 
    // Iterating through each element in array
    foreach($arr[$keys[$i]] as $key => $value) {
        $f = 0;
         
        for($j = 0; $j < count($arr); $j++) {
             
            if($i != $j) {
                foreach($arr[$keys[$j]] as $key1 => $value1) {
     
                    // Checking for duplicacy
                    if(($key1 == $key) && ($value == $value1)) {
                        $f = 1;
     
                        // String index where the duplicate
                        // array exists
                        $dup_ind = $j;
                    }
                }
            }
        }
    }
     
    // If duplicate is found
    if($f ==1 ) {
        $temp_arr = array();
        array_push($temp_arr, $arr[$i]);
         
        // Merge both the arrays
        array_push($temp_arr, $arr[$dup_ind]);
         
        // Remove the duplicate element from original array
        unset($arr[$dup_ind]);
         
        // Finally push in the result array
        array_push($myarray, $temp_arr);
    }
    else {
         
        // Directly push in the result array
        array_push($myarray, $arr[$keys[$i]]);
    }
}
 
print_r($myarray);
 
?>


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. 
 

php




<?php
 
$arr = array(
    array('Roll'=>43, 'name'=>'Geeks', 'subject'=>'Course-011'),
    array('Roll'=>38, 'name'=>'GFG', 'subject'=>'Course-011'),
    array('Roll'=>26, 'name'=>'GeeksforGeeks', 'subject'=>'Course-011'),
    array('Roll'=>31, 'name'=>'gfg', 'subject'=>'Course-012')
);
 
foreach($arr as $k => $v) {
    $new_arr[$v['subject']][]=$v;
}
 
print_r($new_arr);
 
?>


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
                )

        )

)

 



Previous Article
Next Article

Similar Reads

PHP multidimensional array search by value
In PHP, multidimensional array search refers to searching a value in a multilevel nested array. There are various techniques to carry out this type of search, such as iterating over nested arrays, recursive approaches and inbuilt array search functions. Iterative Approach: Iterating over the array and searching for significant match is the simplest
4 min read
How to search by key=&gt;value in a multidimensional array in PHP ?
In PHP, multidimensional array search refers to searching a key=&gt;value in a multilevel nested array. This search can be done either by the iterative or recursive approach. Recursive Approach: Check if the key exists in a multidimensional array and the value of a key is equal to required one then the result stored in an array and also recur throu
3 min read
Merge Two Arrays & Remove Duplicate Items in PHP
Given two arrays, the task is to merge both arrays and remove the duplicate elements from from merged array in PHP. Below are the approaches to merge two arrays and remove duplicate items in PHP: Table of Content Using array_merge() and array_unique() FunctionUsing array_merge() with array_flip() FunctionUsing array_merge() with array_values() and
3 min read
Sort a multidimensional array by date element in PHP
Sorting a multidimensional array by element containing date. Use the usort() function to sort the array. The usort() function is PHP builtin function that sorts a given array using user-defined comparison function. This function assigns new integral keys starting from zero to array elements. Syntax: boolean usort( $array, "function_name") Parameter
2 min read
Convert multidimensional array to XML file in PHP
Given a multi-dimensional array and the task is to convert this array into an XML file. To converting the multi-dimensional array into an xml file, create an XML file and use appendChild() and createElement() function to add array element into XML file. Example: First, create a PHP Multidimensional Array for converting that array into the XML file
2 min read
How to check an array is multidimensional or not in PHP ?
Given an array (single-dimensional or multi-dimensional) and the task is to check the given array is multi-dimensional or not. There are few methods to check an array is multi-dimensional or not. The function count() and count_recursive() will give wrong result if the array containing a sub-array which is empty, and the other one is using the rsort
2 min read
Multidimensional Associative Array in PHP
PHP Multidimensional array is used to store an array in contrast to constant values. Associative array stores the data in the form of key and value pairs where the key can be an integer or string. Multidimensional associative array is often used to store data in group relation. Creation: We can create a multidimensional associative array by mapping
4 min read
Converting all keys into snake case in multidimensional array in PHP
In the Snake case, we need to convert a given sentence or a word to a style of writing where all upper case characters will be replaced with lower case and all the gaps will be replaced with an underscore(_). In this article, we will see how to find the snake case of the all keys of a given array. Here, we need to check each of the elements present
4 min read
Multidimensional arrays in PHP
Multi-dimensional arrays are such type of arrays which stores an another array at each index instead of single element. In other words, define multi-dimensional arrays as array of arrays. As the name suggests, every element in this array can be an array and they can also hold other sub-arrays within. Arrays or sub-arrays in multidimensional arrays
4 min read
How to Use Foreach Loop with Multidimensional Arrays in PHP?
Given a Multi-dimensional array, the task is to loop through array in PHP. The foreach loop is a convenient way to iterate over arrays in PHP, including multidimensional arrays. When dealing with multidimensional arrays, you can use nested foreach loops to access and process each element. In this article, we will explore how to use foreach loops to
2 min read
Article Tags :