3v4l.org

run code in 500+ PHP versions simultaneously
<?php $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);
Output for 7.4.0 - 7.4.33, 8.0.1 - 8.0.30, 8.1.0 - 8.1.34, 8.2.0 - 8.2.30, 8.3.0 - 8.3.30, 8.4.1 - 8.4.21, 8.5.0 - 8.5.6
array ( 0 => array ( 'bb' => 1000, 'xx' => 'wsad', 'yy' => array ( 'aa' => 1234, 'cc' => 2345, ), ), 1 => array ( 'xx' => 'wsad', 'yy' => array ( 'aa' => 1234, 'bb' => 2000, 'cc' => 2345, ), ), 2 => array ( 'xx' => 'wsad', 'yy' => array ( 'aa' => 1234, 'bb' => 2000, 'cc' => 2345, ), ), )

preferences:
111.98 ms | 1321 KiB | 4 Q