Reputation: 3097
I have an array which I'm sure there are some duplicate values in it, I want to search in this array and find the duplicate values and return the key of that array.
let me explain with an example, this is my array:
[
0 => [
'name' => 'name0',
'family' => 'family0',
'email' => '[email protected]',
'rate' => 10
],
1 => [
'name' => 'name1',
'family' => 'family1',
'email' => '[email protected]',
'rate' => 4
],
2 => [
'name' => 'name0',
'family' => 'family0',
'email' => '[email protected]',
'rate' => 6
]
];
Now, I want to search in this array by name
, family
, and email
at the same time and return the key of the parent (in this example 0 and 2). because I want to create a new array like this :
[
0 => [
'name' => 'name0',
'family' => 'family0',
'email' => '[email protected]',
'rate' => [
10,
6
]
],
1 => [
'name' => 'name1',
'family' => 'family1',
'email' => '[email protected]',
'rate' => [
4
]
],
];
How can I do this in PHP?
Upvotes: 0
Views: 56
Reputation: 11642
You can use array-reduce and use the 3 similar fields as keys.
Define a function who create the key and set or add rate:
function combineRate($carry, $item) {
$k = implode('###', array($item['name'], $item['family'], $item['email']));
if (isset($carry[$k]))
$carry[$k]['rate'][] = $item['rate'];
else {
$item['rate'] = [$item['rate']];
$carry[$k] = $item;
}
return $carry;
}
Call it with empty array:
$res = array_values(array_reduce($a, 'combineRate', array()));
Live example: 3v4l
Upvotes: 4