views:

67

answers:

3

I'm trying to do a simple word cloud exercise in PHP but with little twist. I have everything else done but I can't figure out how to do a loop that combines the words.

Here's example that will make it little bit easier to understand what I'm trying to do:

I have array like this:

$arr = array('linebreak','indent','code','question','prefer','we','programming')

Now I'm trying to do a function that starts going thru that array and gives me arrays like these:

Array( [0] => 'linebreak' [1] => 'linebreak indent' [2] => 'linebreak indent code' )

Array( [0] => 'indent' [1] => 'indent code' [2] => 'indent code question' )

So basically it goes thru the original words array word by word and makes these little arrays that has 1 to 5 next words combined.

A: 
    $arr = array('linebreak','indent','code','question','prefer','we','programming');
    $val = '';
    foreach($arr as $key=>$value)
    {
        $val .= ' '.$value;
        $newArr[] = $val;
    }

print_r($newArr);
dfilkovi
That gets the first array (`Array( [0] => 'linebreak' [1] => 'linebreak indent' [2] => 'linebreak indent code' )`) but ignores the rest (`Array( [0] => 'indent' [1] => 'indent code' [2] => 'indent code question' )`, etc.).
dnagirl
A: 
$a = array('linebreak','indent','code','question','prefer','we','programming');

for($i = 0; $i < count($a); $i++) {
    $p = array();
    for($k = $i; $k < count($a); $k++) {
     $p[] = $a[$k];
     $r[] = implode(' ', $p);
    }
}

print_r($r);
stereofrog
This seems to have the correct idea but it doesn't limit how many words max per $r. Now with few thousand words in $a it uses more than 3GB of memory :)
Jim
Sorry, but this is all I can do for you. Feel free to improve this code as necessary. This would be a very simple improvement (hint: look at the upper limit in the inner loop).
stereofrog
A: 

Recursion may be the way to go. I haven't exhaustively checked the below for syntax.

function descend($arr, $offset=0) {
  global $holder;

  $tmp=array_slice($arr,$offset,5); //limits the result set for each starter word to 5 or fewer children

  foreach($tmp as $word) {
    $val .= ' '.$word;
    $holder[$offset][]=$val;
  }
  $offset++;

  if($offset<count($arr)) descend($arr,$offset);
}

$arr = array('linebreak','indent','code','question','prefer','we','programming');
$holder = descend($arr);
dnagirl
This seems to have same problem than stereofrog's solution. It doesn't limit word count per array at all.
Jim
good point. Fortunately, `array_slice()` can supply the limit
dnagirl