Alex Kneller Alex Kneller - 3 months ago 5x
PHP Question

Combine arrays that have same value

I have array like this


if sub arrays share same value they should be be merged to one array

expected output:


I`m trying to avoid doing foreach inside foreach for solving this.


This is solution I get for now.

    $sortedArray = sortFunction($arr,0,array());

function sortFunction($old,$index,$new) {
    if ($index == sizeof($old)) return $new;

    for ($i = 0; $i<sizeof($new); $i++) {
        if (count(array_intersect($new[$i],$old[$index]))) {
            $new[$i] = array_unique(array_merge($old[$index],$new[$i]), SORT_REGULAR);
            return sortFunction($old,$index + 1,$new);

    $new[] = $old[$index];
    return sortFunction($old,$index + 1,$new);