脚本宝典收集整理的这篇文章主要介绍了在php中连接n个数组的值,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
例如,如果数组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
以上是脚本宝典为你收集整理的在php中连接n个数组的值全部内容,希望文章能够帮你解决在php中连接n个数组的值所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。