[Solved] php – array intersect and merge


When number of other values is just one:

$array = [
    ['xx', 123],
    ['xx', 523],
    ['xx', 783],
    ['yy', 858],
    ['yy', 523],
    ['xx', 235],
];


$result = [];
foreach ($array as $row) {
    list($key, $value) = $row;
    if (!array_key_exists($key, $result)) {
        $result[$key] = [$key];
    }
    $result[$key][] = $value;
}

More generic solution for any number of other values:

$array = [
    ['xx'],
    ['xx', 523],
    ['xx', 783, 111],
    ['yy', 858, 222, 333],
    ['yy', 523, 444, 555, 666],
    ['xx', 235, 777, 888],
];

$result = [];
foreach ($array as $row) {
    $key = array_shift($row);
    if (!array_key_exists($key, $result)) {
        $result[$key] = [$key];
    }
    $result[$key] = array_merge($result[$key], $row);
}

Also, in the last case array_merge() may be replaced by array_push() with unpacked arguments:

if (sizeof($row) > 0) {
    array_push($result[$key], ...$row);
}

solved php – array intersect and merge