Reputation: 171
I have an array like this.
Array
(
[0] => Array
(
[0] => Array
(
[id] => 123
[name] => abc
[age] => 21
)
[1] => Array
(
[id] => 456
[name] => abc
[age] => 25
)
[2] => Array
(
[id] => 789
[name] => ghi
[age] => 40
)
)
)
what i want to do is find any duplicates name in that array and place that in a new array.So finally my array have to be like this.
Array
(
[0] => Array
(
[0] => Array
(
[id] => 123
[name] => abc
[age] => 21
)
[1] => Array
(
[id] => 789
[name] => ghi
[age] => 40
)
)
[1] => Array
(
[0] => Array
(
[id] => 456
[name] => abc
[age] => 25
)
)
)
I'm struggling on how to do that.can any body pls help me to fix this?
Upvotes: 1
Views: 55
Reputation: 7948
You can just use a simple foreach for this, you could just push the duplicate array to the next dimension if it sees one. Example:
$values = array(
array(
array('id' => 123, 'name' => 'abc', 'age', 21),
array('id' => 456, 'name' => 'abc', 'age', 25),
array('id' => 789, 'name' => 'ghi', 'age', 40),
),
);
foreach($values as $batch) {
$temp = array();
foreach($batch as $key => $value) {
if(!isset($temp[$value['name']])) {
$temp[$value['name']] = $value; // temporary storage
} else {
unset($batch[$key]);
$values[][] = $value; // push it outside this batch
}
}
}
echo '<pre>';
print_r($values);
Upvotes: 1