Home  >  Article  >  Backend Development  >  如何用return遍历无限数组

如何用return遍历无限数组

WBOY
WBOYOriginal
2016-06-13 10:21:481207browse

怎么用return遍历无限数组?
$arr=array(array(6,66),8);
function arr_p($arr){
  foreach ($arr as $v){
  if(is_array($v)){
  arr_p($v);
  }else{
  echo $v."
";}
  }
}
arr_p($arr);
?>

这段是直接echo出的,现在想用return,不知如何下手,希望高人指点一下!(小弟是php初学者)

------解决方案--------------------
$arr=array(array(6,66),8);
function arr_p($arr){
$r = '';
foreach ($arr as $v){
if(is_array($v)){
$r .= arr_p($v);
}else{
$r .= $v."
";}
}
return $r;
}
echo arr_p($arr);
------解决方案--------------------

PHP code
function arr_p($arr){  $r = ''; //因为要返回数据,所以要有一个载体  foreach ($arr as $v){    if(is_array($v)){ //如果是数组,据递归进入      $r .= arr_p($v); //接住返回的数据    }else{      $r .= $v."<br>"; //不是数组,不也要保存数据吗    }  }  return $r; //返回数据}<div class="clear">
                 
              
              
        
            </div>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn