Alex Kneller Alex Kneller - 1 year ago 62
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.

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download