我有一个未知数量的数组,每个数组包含未知数量的单词.我希望连接每个列表中的值,以便将单词的所有可能变体存储到最终数组中.
例如,如果数组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','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