如何使用PHP从数组创建子串?

时间:2010-04-19 21:06:30

标签: php arrays

我有一组数据如下:

2008, Honda, Accord, Used, Car

我正试图想办法从数组中的每个项目中创建一些子字符串。例如,我想循环每个项目并创建以下子字符串:

2008
2008 Honda
2008 Accord
2008 Used
2008 Car
2008 Honda Accord
2008 Honda Used
2008 Honda Car
2008 Accord Honda
2008 Accord Used
2008 Accord Car
2008 Used Honda
2008 Used Accord
2008 Used Car
2008 Car Honda
2008 Car Accord
2008 Car Used
Honda
Honda 2008
Honda Accord
Honda Used
Honda Car
Honda 2008 Accord
Honda 2008 Used
etc ...

我需要确保没有重复创建,我需要阻止它两次添加相同的单词(例如:本田本田或2008本田2008 - 我不想要那个)。有没有人写过这样的东西,或者知道我在哪里可以找到一个同样方式的脚本?

3 个答案:

答案 0 :(得分:2)

您可以声明二进制数组X,如{0,0,0,0,1}。 并增加二进制逻辑。每次增加后,您将打印此规则的生成字符串。如果在数组X字上有1,则字i出现,如果0字不存在。

您可以使用它的功能:

string decbin  (  int $number  )

您可以在以下网址找到她的文档: http://pl2.php.net/manual/en/function.decbin.php

当您到达由唯一填充的阵列时,您的算法会停止。 在十进制表示中是:

pow(2, sizeof(X)) - 1

答案 1 :(得分:2)

这个怎么样:

<?php

$vals = array('2008', 'Honda', 'Accord', 'Used', 'Car');

function make_keyword_strings($array, $maxdepth = false, $prefix = '') {
  $ret = array();
  // if we are tracking depths, subtract one from the depth:
  $newdepth = $maxdepth === false ? false : $maxdepth-1;
  if ($newdepth < 0) return $ret; // we went over our depth
  foreach($array as $key => $value) {
    $temp = $array;
    unset($temp[$key]); // remove the current key

    // add our current value ($prefix.$value), and recursively call the function with
    // a new prefix.
    $ret = array_merge($ret, 
             array(trim($prefix.$value)), 
             (array) make_keyword_strings($temp, $newdepth, $prefix.$value.' '));
  }
  return $ret;
}

echo(implode("\n",make_keyword_strings($vals,3)));

----结果输出----

2008
2008 Honda
2008 Honda Accord
2008 Honda Used
2008 Honda Car
2008 Accord
2008 Accord Honda
2008 Accord Used
2008 Accord Car
2008 Used
2008 Used Honda
2008 Used Accord
2008 Used Car
2008 Car
2008 Car Honda
2008 Car Accord
2008 Car Used
Honda
Honda 2008
Honda 2008 Accord
Honda 2008 Used
Honda 2008 Car
Honda Accord
Honda Accord 2008
Honda Accord Used
Honda Accord Car
Honda Used
Honda Used 2008
Honda Used Accord
Honda Used Car
Honda Car
Honda Car 2008
Honda Car Accord
Honda Car Used
Accord
Accord 2008
Accord 2008 Honda
Accord 2008 Used
Accord 2008 Car
Accord Honda
Accord Honda 2008
Accord Honda Used
Accord Honda Car
Accord Used
Accord Used 2008
Accord Used Honda
Accord Used Car
Accord Car
Accord Car 2008
Accord Car Honda
Accord Car Used
Used
Used 2008
Used 2008 Honda
Used 2008 Accord
Used 2008 Car
Used Honda
Used Honda 2008
Used Honda Accord
Used Honda Car
Used Accord
Used Accord 2008
Used Accord Honda
Used Accord Car
Used Car
Used Car 2008
Used Car Honda
Used Car Accord
Car
Car 2008
Car 2008 Honda
Car 2008 Accord
Car 2008 Used
Car Honda
Car Honda 2008
Car Honda Accord
Car Honda Used
Car Accord
Car Accord 2008
Car Accord Honda
Car Accord Used
Car Used
Car Used 2008
Car Used Honda
Car Used Accord

答案 2 :(得分:0)

您想要做的是:

  1. 创建数组L
  2. 对于原始文本中的每个单词
    • 如果该字词不在L中,请将该字词移至L
  3. 然后,只需生成所需类型的所有可能排列即可。