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

03-Apr-2023

.

Admin

Hi Guys,

In this example,I will learn you how to merge the duplicate value in multidimensional array in php.you can easy and simply merge the duplicate value in multidimensional array in php.

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.

Example 1:


<?php

$arr = array(

array('Roll'=>43, 'name'=>'Good', 'subject'=>'Course-015'),

array('Rool'=>38, 'name'=>'Nice', 'subject'=>'Course-012'),

array('Rool'=>43, 'name'=>'Good', 'subject'=>'Course-015')

);

// 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);

?>

Example 2:

In this example the duplicate field is more than two.

<?php

$arr = array(

array('Roll'=>43, 'name'=>'Good', 'subject'=>'Course-015'),

array('Roll'=>38, 'name'=>'Nice', 'subject'=>'Course-015'),

array('Roll'=>26, 'name'=>'Goods', 'subject'=>'Course-015'),

array('Roll'=>31, 'name'=>'Good Nice', 'subject'=>'Course-012')

);

foreach($arr as $k => $v) {

$new_arr[$v['subject']][]=$v;

}

print_r($new_arr);

?>

It will help you...

#PHP