Reputation: 13
I have a multi-dimensional array like the following:
$arr = [
['name' => 'John', 'age' => 10, 'gender' => 'male', 'info' => ''],
['name' => 'Jeniffer', 'age' => 12, 'gender' => 'female', 'info' => ''],
['name' => 'John', 'age' => 10, 'gender' => 'male', 'info' => '']
];
I want to detect whether one of the arrays that it contains is duplicated. If it's a duplicated array, I want to append index of info with "DUPLICATED".
For example, here's what the final result (output) would look like when applying the logic to the original multi-dimensional array:
$arr = [
['name' => 'John', 'age' => 10, 'gender' => 'male', 'info' => 'DUPLICATED'],
['name' => 'Jeniffer', 'age' => 12, 'gender' => 'female', 'info' => ''],
['name' => 'John', 'age' => 10, 'gender' => 'male', 'info' => 'DUPLICATED']
];
How can I do this?
I have tried using the following code:
$uploadData = array_unique($uploadData->toArray(), SORT_REGULAR);
…but it only produces a unique array (i.e., it eliminates all duplicates). This is not what I want. I just want the duplicates to be annotated with an indication that they are a duplicate.
Upvotes: 0
Views: 69
Reputation: 47991
info
element of that row (but don't update the value).DUPLICATED
.Code: (Demo)
foreach ($arr as &$row) {
$compositeKey = implode('_', $row);
if (isset($info[$compositeKey])) { // not first occurrence
$info[$compositeKey] = 'DUPLICATED'; // overwrite reference value
$row['info'] = 'DUPLICATED'; // update current row's value
} else {
$info[$compositeKey] = &$row['info']; // first occurrence, assign reference
}
}
var_export($arr);
Upvotes: 1