Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping an array of similar words

Tags:

php

I have an array with a bunch of words. E.g:

array( developer,develop,development,design,designer,designing )

I want to be able to group these words together with their similar words so I'd get something like this:

array(
   array( develop, developer, development ),
   array( design, designer, designing ),
);

What would be the best way to do this in PHP?

like image 939
Luke Avatar asked Dec 06 '25 09:12

Luke


2 Answers

You can do it easily using metaphone():

$result = array();
foreach ($array as $word) {
    $result[metaphone($word, 2)][] = $word;
}

print_r($result); will show:

Array
(
    [TF] => Array
        (
            [0] => developer
            [1] => develop
            [2] => development
        )

    [TS] => Array
        (
            [0] => design
            [1] => designer
            [2] => designing
        )
)
like image 125
Carlos Avatar answered Dec 08 '25 22:12

Carlos


A way is comming to my mind

$array = array( 'developer','develop','development','design','designer','designing' );

function matchWords(array $in,$pad='4')
{
    $ret = array();
    foreach ($in as $v) {
        $sub = substr($v, 0, $pad);
        if (!isset($ret[$sub])) {
            $ret[$sub] = array();
        }
        $ret[$sub][] = $v;
    }

    return array_values($ret);
}

print_r(matchWords($array,4));

Array
(
    [0] => Array
        (
            [0] => developer
            [1] => develop
            [2] => development
        )

    [1] => Array
        (
            [0] => design
            [1] => designer
            [2] => designing
        )
)

This matches the $pad first letters of your array values and create a key on it.

like image 23
Touki Avatar answered Dec 08 '25 21:12

Touki