There will not be a non-loop way to accomplish this. Maybe you are seeking function-based syntax, but for this scenario I think this will only introduce unnecessary convolution.
For best efficiency, generate a result array that doubles as a lookup array. If the key already exists in the result array, you only need to push the [1]
value into that row. If you wish to reindex the result, just call array_values()
on it.
Code: (Demo)
$array1 = [
[10, 'Some Name..'],
[11, 'Some Name..'],
[13, 'Some Name..'],
];
$array2 = [
[13, 'Viewed']
];
$result = [];
foreach (array_merge($array1, $array2) as $row) {
if (!isset($result[$row[0]])) {
$result[$row[0]] = $row;
} else {
$result[$row[0]][] = $row[1];
}
}
var_export($result);
Functional style: (Demo)
var_export(
array_reduce(
array_merge($array1, $array2),
function($result, $row) {
if (!isset($result[$row[0]])) {
$result[$row[0]] = $row;
} else {
$result[$row[0]][] = $row[1];
}
return $result;
}
)
);
Because this task needs to merge on the first column and retain (append) all second column values, a conditionless approach can be used for the same result.
Code: (Demo)
$result = [];
foreach (array_merge($array1, $array2) as [$id, $value]) {
$result[$id][0] = $id;
$result[$id][] = $value;
}
var_export($result);