php数组递归输出,该怎么解决

WBOY
Release: 2016-06-13 12:55:46
Original
714 people have browsed it

php数组递归输出

本帖最后由 ecshop528 于 2013-01-21 12:54:22 编辑 $ar = array('0'=>array('name'=>'name1','age'=>'age1'),'1'=>array('name'=>'name2','age'=>'age2'),'2'=>array('name'=>'name3','age'=>'age3'));

想通过递归,输入以下字符串



name3-age3

name2-age2

name1-age1

$ar = array('0'=>array('name'=>'name1','age'=>'age1'),'1'=>array('name'=>'name2','age'=>'age2'),'2'=>array('name'=>'name3','age'=>'age3'));<br />
deep_child($ar);<br />
function deep_child($ar = array()){<br />
	static $str = '';<br />
	static $i=0;<br />
	<br />
	if($ar[$i]){<br />
		echo '<div id="a">';<br />
		$s =  $ar[$i]['name']."-".$ar[$i]['age'];<br />
		$i++;<br />
		deep_child($ar);<br />
		echo $s;<br />
		echo '</div>';<br />
	<br />
	}<br />
}
Copy after login


这样写好象能输入,不知道有没其他写法。。


------解决方案--------------------
静态变量可不是随便可用的
$ar[0] = array('0'=>array('name'=>'name1','age'=>'age1'),'1'=>array('name'=>'name2','age'=>'age2'),'2'=>array('name'=>'name3','age'=>'age3'));<br />
$ar[1] = array('0'=>array('name'=>'name1','age'=>'age1'),'1'=>array('name'=>'name2','age'=>'age2'),'2'=>array('name'=>'name3','age'=>'age3'));<br />
for($i=0;$i<2;$i++){<br />
    echo deep_child($ar[$i]);<br />
     <br />
}<br />
function deep_child($ar = array(), $i=0){<br />
    $str = '';<br />
//    static $i=0;<br />
     <br />
    if(isset($ar[$i])){<br />
        $str.= '<div id="a">'.PHP_EOL;<br />
        $str.=  $ar[$i]['name']."-".$ar[$i]['age'].PHP_EOL;<br />
        $i++;<br />
        $str.=deep_child($ar, $i);<br />
         <br />
        $str.= '</div>'.PHP_EOL;<br />
     <br />
    }<br />
    return $str;<br />
}
Copy after login

name1-age1

name2-age2

name3-age3




name1-age1

name2-age2

name3-age3



Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template