PHP array recursive output, how to solve

Source: Internet
Author: User
PHP array Recursive output
This post was last edited by ecshop528 on 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 '));

To use recursion, enter the following string



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 '));
Deep_child ($ar);
function Deep_child ($ar = Array ()) {
static $str = ';
static $i = 0;

if ($ar [$i]) {
Echo ';
$s = $ar [$i] [' name ']. " -". $ar [$i] [' age '];
$i + +;
Deep_child ($ar);
Echo $s;
Echo ';

}
}


This kind of writing seems to be able to input, do not know if there is no other way to write.


------Solution--------------------
Static variables are not freely available.
$ar [0] = array (' 0 ' =>array (' name ' = ' = ' name1 ', ' age ' = ' age1 '), ' 1 ' =>array (' name ' = = ' name2 ', ' age ' = ') Age2 '), ' 2 ' =>array (' name ' = ' name3 ', ' age ' = ' age3 '));
$ar [1] = array (' 0 ' =>array (' name ' = ' = ' name1 ', ' age ' = ' age1 '), ' 1 ' =>array (' name ' = = ' name2 ', ' age ' = ') Age2 '), ' 2 ' =>array (' name ' = ' name3 ', ' age ' = ' age3 '));
for ($i =0; $i <2; $i + +) {
Echo Deep_child ($ar [$i]);

}
function Deep_child ($ar = Array (), $i =0) {
$str = ";
static $i = 0;

if (Isset ($ar [$i])) {
$str. = '. Php_eol;
$str. = $ar [$i] [' name ']. " -". $ar [$i] [' age ']. Php_eol;
$i + +;
$str. =deep_child ($ar, $i);

$str. = '. Php_eol;

}
return $str;
}

Name1-age1

Name2-age2

Name3-age3




Name1-age1

Name2-age2

Name3-age3



  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.