EvilZone

Programming and Scripting => Web Oriented Coding => : Code.Illusionist January 17, 2014, 02:50:13 PM

: Foreach loop trough two dimensional array
: Code.Illusionist January 17, 2014, 02:50:13 PM
Greetings EZ members. I recently started learning PHP and I understand how foreach loop work on one dimensional array, but I failed to understand how that can be used on two dimensional array. I have code like this:

: (php)
<?php
$person = array(
array("Michael","14","New York"),
array("Peter","21","London"),
array("John","30","Moskva")
);
?>
Is there any way to call members of the array to be presented like this:

Michael is 14 years old and he live in New York.
Peter is 21 years old and he live in London.
John is 30 years old and he live in Moskva.
: Re: Foreach loop trough two dimensional array
: proxx January 17, 2014, 03:33:50 PM
Not perse php specific but bascially you can nest loops to extract data the same way one could populate them.
: Re: Foreach loop trough two dimensional array
: Code.Illusionist January 17, 2014, 04:46:23 PM
Could you please show me that on one example?
: Re: Foreach loop trough two dimensional array
: Kulverstukas January 17, 2014, 04:59:51 PM
A loop inside a loop is what proxx meant.
Here's some pseudocode

Nested loops:
:
foreach (item_in_array) {
    foreach (item_in_array) {
        // do shit
    }
}

or what works in your case:

:
foreach (item_in_array) {
        print item[0] is item[1] years old and he live in item[2].
    }
}
: Re: Foreach loop trough two dimensional array
: Code.Illusionist January 17, 2014, 05:04:32 PM
: (php)
<?php
        $person 
= array(
        array(
"Michael","14","New York"),
        array(
"Peter","21","London"),
        array(
"John","30","Moskva")
        );
       foreach (
$person as $item) echo "{$item[0]} is {$item[1]} years old and he live in {$item[2]} <br />";
?>
I did it, thank you both, it worked perfectly!!! May the cookies be with you guys. :D
: Re: Foreach loop trough two dimensional array
: ande January 17, 2014, 05:04:41 PM
:
foreach (item_in_array) {
        print item[0] is item[1] years old and he live in item[2].
    }
}

[gist]anonymous/8475967[/gist]


EDIT: Awww, too late. Oh well.