栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在PHP中连接n个数组的值

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在PHP中连接n个数组的值

您可以将所有单词数组放到一个数组中,并使用如下 递归 函数:

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 cardog food bikedog tooth cardog tooth bikecat food carcat food bikecat tooth carcat 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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/443117.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号