Jr. Developer
Jr. Developer

Reputation: 13

Update column value in each row where the row is identical to another row in the same 2d array

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

Answers (1)

mickmackusa
mickmackusa

Reputation: 47991

  • Iterate the input array only one time.
  • Create a unique identifier by joining all row values with a delimiting character.
  • If the identifier has not yet been encountered, assign a reference variable to the info element of that row (but don't update the value).
  • If the identifier has been encountered before, update the current row and the reference variable with 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

Related Questions