Merging duplicate values into multi-dimensional array in PHP

PHPServer Side ProgrammingProgramming

To merge duplicate values into multi-dimensional array in PHP, the code is as follows −

Example

 Live Demo

<?php
$my_arr = array(
   array('Age'=>23, 'name'=>'Joe', 'hobby'=>'Cycling'),
   array('Age'=>26, 'name'=>'Hannah', 'hobby'=>'Rowing'),
   array('Age'=>30, 'name'=>'Dev', 'hobby'=>'Cycling'),
   array('Age'=>30, 'name'=>'Dev', 'hobby'=>'Cycling')
);
foreach($my_arr as $entry => $vals)
{
   $new_vals[$vals['hobby']][]=$vals;
}
echo "The unique array elements are ";
print_r($new_vals);
?>

Output

The unique array elements are Array
(
   [Cycling] => Array
   (
      [0] => Array
      (
         [Age] => 23
         [name] => Joe
         [hobby] => Cycling
      )

      [1] => Array
      (
         [Age] => 30
         [name] => Dev
         [hobby] => Cycling
      )

      [2] => Array
      (
         [Age] => 30
         [name] => Dev
         [hobby] => Cycling
      )

   )

   [Rowing] => Array
   (
      [0] => Array
      (
         [Age] => 26
         [name] => Hannah
         [hobby] => Rowing
      )

   )

)

An array of values is defined that maps age, name and hobby to certain values. The ‘foreach’ loop is used to iterate over the array values and a new value is assigned to one of the entries in the array. The value that was previously duplicate will now be merged into a single entry, thereby avoiding storage of duplicate values.

raja
Published on 01-Jul-2020 10:56:50
Advertisements