从数组生成字符串序列

时间:2017-07-05 09:16:34

标签: php arrays string

我有一个字母数组:

Foo foo = (Foo)obj;

如何生成下一个字符串:

$ga = array_merge(range('A', 'Z'), range(0,9));

谢谢!

1 个答案:

答案 0 :(得分:1)

这可能是最简单的方法:

<?php
$alphabeth = array_merge(range('A', 'Z'), range(0,9));
$character = [];
foreach ($alphabeth as $character[0]) {
  foreach ($alphabeth as $character[1]) {
    foreach ($alphabeth as $character[2]) {
      foreach ($alphabeth as $character[3]) {
        $catalog[] = vsprintf('%s%s%s%s', $character);
      }
    }
  }
}
print_r($catalog);

输出显然是:

Array
(
    [0] => AAAA
    [1] => AAAB
    [2] => AAAC
    [3] => AAAD
    .....
    [1679613] => 9997
    [1679614] => 9998
    [1679615] => 9999
)

更新:

如果我说得对,你在下面的评论中提到你需要将这些字符串填充到一个文件中。如果是这样,那么这将成为顺序处理的一个例子,它可以显着减少脚本内存占用,如评论中所述:

<?php
$alphabeth = array_merge(range('A', 'Z'), range(0,9));
$handle = fopen('/home/arkascha/catalog.list', 'w');
foreach ($alphabeth as $character[0]) {
  foreach ($alphabeth as $character[1]) {
    foreach ($alphabeth as $character[2]) {
      foreach ($alphabeth as $character[3]) {
        fwrite($handle, vsprintf("%s%s%s%s\n", $character));
      }
    }
  }
}
fclose($handle);