2011-02-17 83 views
0

我以下面的單詞爲數組作爲示例。php數組操作幫助

$words = array('hello','world','wad','up','yo','etc'); 

我要的是下一個數組與上述

$phrase2 = array('hello world', 'world wad', 'wad up', 'up yo', 'yo etc'); 
$phrase3 = array('hello world wad', 'world wad up', 'wad up yo', 'up yo etc'); 
$phrase4 = array('hello world wad up', 'world wad up yo', 'wad up yo etc'); 
$phrase5 = array('hello world wad up yo', 'world wad up yo etc'); 

操縱下,我希望我的問題是清楚的。

+5

這是家庭作業嗎? – 2011-02-17 19:50:24

+0

哦,現在我明白了。我現在會照顧它。不固定可以不時或多或少。我正在開發一個網站,我需要使用這些知識。 – Yalamber 2011-02-17 20:24:37

回答

2

切片數組,然後破滅的結果:

$words = array('hello','world','wad','up','yo','etc'); 
$phrase2 = array(); 
$phrase3 = array(); 
$phrase4 = array(); 
$lim = sizeof($words); 
for($i=0;$i<$lim;$i++) 
{ 
    if($i < $lim - 1) 
     $phrase2[] = implode(" ",array_slice($words,$i,2)); 
    if($i < $lim - 2) 
     $phrase3[] = implode(" ",array_slice($words,$i,3)); 
    if($i < $lim - 3) 
     $phrase4[] = implode(" ",array_slice($words,$i,4)); 
} 
+0

您缺少`$ phrase5`,但它有效:http://codepad.org/rvzCThNK – Shikiryu 2011-02-17 19:59:18

3

代替phrase2 $,$ phrase3,......我的代碼使用$詞組[2],$短語[3],...

但是,如果你想使用$ phrase2,$ phrase3,$ phrase4,然後只需將下面的代碼添加到我的結尾:

$phrase2 = $phrase[2]; 
$phrase3 = $phrase[3]; 
$phrase4 = $phrase[4]; 
$phrase5 = $phrase[5]; 

這裏我的代碼,只是試試吧!

<?php 
$words = array('hello','world','wad','up','yo','etc'); 
$phrase = array(); 
for($i=2; $i<=count($words); $i++) 
{ 
    foreach($words as $key => $value) 
    { 
     if($key <= count($words)-$i) 
     { 
      $phrase_value[] = $value; 

      for($j=1; $j<$i; $j++) 
      { 
       $phrase_value[] = $words[$key+$j]; 
      } 

      $phrase[$i][] = implode(' ', $phrase_value); 
      unset($phrase_value); 
     } 
    } 
} 
// this deletes the last array in phrase 
array_pop($phrase); 
?> 

和輸出是這樣的:

Array 
(
    [2] => Array 
     (
      [0] => hello world 
      [1] => world wad 
      [2] => wad up 
      [3] => up yo 
      [4] => yo etc 
     ) 

    [3] => Array 
     (
      [0] => hello world wad 
      [1] => world wad up 
      [2] => wad up yo 
      [3] => up yo etc 
     ) 

    [4] => Array 
     (
      [0] => hello world wad up 
      [1] => world wad up yo 
      [2] => wad up yo etc 
     ) 

    [5] => Array 
     (
      [0] => hello world wad up yo 
      [1] => world wad up yo etc 
     ) 

    [6] => Array 
     (
      [0] => hello world wad up yo etc 
     ) 

) 
1

我想這對我的編程工作。

<?php 

$src1 = "hello world wad up yo etc"; 
$words = explode(" ",$src1); 
$length = count($words); 
print_r($words); 

$phrases = array(); 

foreach(range(2,5) as $span){ 
    $shifter = create_function("\$n","{ global \$words; return join(\" \", array_slice(\$words,\$n,$span)); }"); 
    $sp = array_map($shifter, range(0, $length - $span)); 
    ###var_dump($sp); 
    $phrases["phrase$span"] = $sp; 
} 

print_r($phrases);