Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP combine arrays on similar elements

I have some data in this format:

even--heaped<br />
even--trees<br />
hardrocks-cocked<br />
pebble-temple<br />
heaped-feast<br />
trees-feast<br />

and I want to end up with an output so that all lines with the same words get added to each other with no repeats.

even--heaped--trees--feast<br />
hardrocks--cocked<br />
pebbles-temple<br />

i tried a loop going through both arrays but its not the exact result I want. for an array $thing:

Array ( [0] => even--heaped [1] => even--trees [2] => hardrocks--cocked [3] => pebbles--temple [4] => heaped--feast [5] => trees--feast )



for ($i=0;$i<count($thing);$i++){
    for ($j=$i+1;$j<count($thing);$j++){
        $first = explode("--",$thing[$i]);
        $second = explode("--",$thing[$j]);

        $merge = array_merge($first,$second);
        $unique = array_unique($merge);

    if (count($unique)==3){
        $fix = implode("--",$unique);
        $out[$i] = $thing[$i]."--".$thing[$j];
    }

}

}

print_r($out);

but the result is:

Array ( [0] => even--heaped--heaped--feast [1] => even--trees--trees--feast [4] => heaped--feast--trees--feast )

which is not what i want. Any suggestions (sorry about the terrible variable names).

like image 302
user2426240 Avatar asked Mar 24 '23 19:03

user2426240


1 Answers

This might help you:

$in = array( 
    "even--heaped",
    "even--trees",
    "hardrocks--cocked",
    "pebbles--temple",
    "heaped--feast",
    "trees--feast"
);

$clusters = array();

foreach( $in as $item ) {

    $words = explode("--", $item);

    // check if there exists a word in an existing cluster...
    $check = false;
    foreach($clusters as $k => $cluster) {
        foreach($words as $word) {
            if( in_array($word, $cluster) ) {
                // add the words to this cluster
                $clusters[$k] = array_unique( array_merge($cluster, $words) );
                $check = true;
                break;
            }
        }
    }

    if( !$check ) {
        // create a new cluster
        $clusters[] = $words;
    }
}

// merge back
$out = array();
foreach( $clusters as $cluster ) {
    $out[] = implode("--", $cluster);
}

pr($out);
like image 120
ilbesculpi Avatar answered Mar 26 '23 09:03

ilbesculpi