我有未知数量的数组,每个数组包含未知数量的单词。我想连接每个列表中的值,以便将单词的所有可能变体存储到最终数组中。
例如,如果数组 1 包含:
dog
cat
数组 2 包含:
food
tooth
数组 3 包含:
car
bike
我希望输出是:
dog food car
dog food bike
dog tooth car
dog tooth bike
cat food car
cat food bike
cat tooth car
cat tooth bike
可能有 3 个以上的列表,每个列表很可能有 2 个以上的词。
我想用 PHP 来做。
如果我知道列表的数量,我就知道该怎么做,尽管这可能不是最节省资源的方法。但是,如果您知道数组的数量,嵌套的 foreach
循环就可以工作。如果你不这样做怎么办?如果有 100 个数组,每个数组包含 100 个单词,有什么方法可以解决这个问题仍然有效。还是1000?
谢谢!
最佳答案
您可以将所有单词数组放入一个数组中并使用这样的递归函数:
function concat(array $array) {
$current = array_shift($array);
if(count($array) > 0) {
$results = array();
$temp = concat($array);
foreach($current as $word) {
foreach($temp as $value) {
$results[] = $word . ' ' . $value;
}
}
return $results;
}
else {
return $current;
}
}
$a = array(array('dog', 'cat'), array('food', 'tooth'), array('car', 'bike'));
print_r(concat($a));
哪个返回:
Array
(
[0] => dog food car
[1] => dog food bike
[2] => dog tooth car
[3] => dog tooth bike
[4] => cat food car
[5] => cat food bike
[6] => cat tooth car
[7] => cat tooth bike
)
但我猜这对于大型数组来说表现不佳,因为输出数组会非常大。
要解决这个问题,您可以使用类似的方法直接输出组合:
function concat(array $array, $concat = '') {
$current = array_shift($array);
$current_strings = array();
foreach($current as $word) {
$current_strings[] = $concat . ' ' . $word;
}
if(count($array) > 0) {
foreach($current_strings as $string) {
concat($array, $string);
}
}
else {
foreach($current_strings as $string) {
echo $string . PHP_EOL;
}
}
}
concat(array(array('dog', 'cat'), array('food', 'tooth'), array('car', 'bike')));
给出:
dog food car
dog food bike
dog tooth car
dog tooth bike
cat food car
cat food bike
cat tooth car
cat tooth bike
使用这种方法也很容易得到“子连接”。只需插入 echo $string 。 PHP_EOL;
在 concat($array, $string);
之前,输出是:
dog
dog food
dog food car
dog food bike
dog tooth
dog tooth car
dog tooth bike
cat
cat food
cat food car
cat food bike
cat tooth
cat tooth car
cat tooth bike
关于php - 在php中连接n个数组的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2246493/