- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Merging duplicate values into multi-dimensional array in PHP
To merge duplicate values into multi-dimensional array in PHP, the code is as follows −
Example
<?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.
- Related Articles
- Multi-Dimensional Array in Javascript
- Reduce a multi-dimensional array in Numpy
- Converting multi-dimensional array to string in JavaScript
- Pushing values into array with multi field set to TRUE?
- Greatest element in a Multi-Dimensional Array in JavaScript
- Split one-dimensional array into two-dimensional array JavaScript
- What is the simplest multi-dimensional array in C#?
- What is a multi-dimensional array in C language?
- PHP Pushing values into an associative array?
- How to access elements from multi-dimensional array in C#?
- Reduce a multi-dimensional array along given axis in Numpy
- Reduce a multi-dimensional array along axis 1 in Numpy
- Reduce a multi-dimensional array along negative axis in Numpy
- Reduce a multi-dimensional array and multiply elements in Numpy
- Reduce a multi-dimensional array and add elements in Numpy

Advertisements