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'));
想通过递归,输入以下字符串
$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
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