Home > Software design >  Move duplicate values of a multidimensional array
Move duplicate values of a multidimensional array

Time:07-19

I'm still learning my way to manage array in more complex ways. I have this case where a multidimensional array can have keys with duplicate values. I only want to check for duplicates for some keys ($specialkeys) and if any are found to be duplicate in $myarray, remove those keys and add them to a new level ('yy').

//The keys to look for duplicate values
static $specialkeys = ['aa', 'bb', 'cc'];

//The array where to look for duplicate values
$myarray = [ 
  0 => [
    'aa' => 1234,
    'bb' => 1000,
    'cc' => 2345,
    'xx' => 'wsad',
  ],
  1 => [
    'aa' => 1234,
    'bb' => 2000,
    'cc' => 2345,
    'xx' => 'wsad',
  ],
  2 => [
    'aa' => 1234,
    'bb' => 2000,
    'cc' => 2345,
    'xx' => 'wsad',
  ]
];

foreach ($specialkeys as $i) {
    //What to do here?
    //Preferred way is to use PHP array functions
    array_column($myarray, $i);
}

Wanted result

$myarray = [ 
  0 => [
    'yy' => ['aa' => 1234, 'cc' => 2345],
    'bb' => 1000,
    'xx' => 'wsad',
  ],
  1 => [
    'yy' => ['aa' => 1234, 'bb' => 2000, 'cc' => 2345],
    'xx' => 'wsad',
  ],
  2 => [
    'yy' => ['aa' => 1234, 'bb' => 2000, 'cc' => 2345],
    'xx' => 'wsad',
  ]
];

CodePudding user response:

Iterate to form a lookup based on encountered duplicates, then iterate again to conditionally modify your rows.

Code: (Demo)

$specialkeys = ['aa', 'bb', 'cc'];

$myarray = [ 
    ['aa' => 1234, 'bb' => 1000, 'cc' => 2345, 'xx' => 'wsad'],
    ['aa' => 1234, 'bb' => 2000, 'cc' => 2345, 'xx' => 'wsad'],
    ['aa' => 1234, 'bb' => 2000, 'cc' => 2345, 'xx' => 'wsad']
];

$lookup = [];
foreach ($myarray as $row) {
    foreach ($specialkeys as $col) {
        $lookup[$col][$row[$col]] ??= -1;
          $lookup[$col][$row[$col]];
    }
}
//var_export($lookup);
foreach ($myarray as &$row) {
    foreach ($specialkeys as $col) {
        if ($lookup[$col][$row[$col]]) {
            $row['yy'][$col] = $row[$col];
            unset($row[$col]);
        }
    }
}
var_export($myarray);
  • Related