Alex Kneller Alex Kneller - 5 months ago 9
PHP Question

Combine arrays that have same value

I have array like this

$arr=[["a","b"],["b","c"],["d","e"],["f","c"]];


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

expected output:

$arr=[["a","b","c","f"],["d","e"]];


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

Answer

This is solution I get for now.

    $arr=[["a","b","c","f"],["d","e"]];
    $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);
}
Comments