
-----------------------------------
iker
Thu Nov 19, 2009 1:15 am

traverse 2d array with foreach()
-----------------------------------
Hey, so i haven't been active on these forums in forever...

I'm having an issue with pulling the size of a 2d array

so heres the boring info if you wanto know what I'm doing

I'm working on a team project for one of my classes and our prof decided that we should do a blackberry web gps based game.. I was put on the php/javascript team (with no past php experience) and I'm having some troubles.
So I have an onClick() java function which enables up to 3 buttons(you click on character and it lets you pick from 3 weapons to attack with).. this is called from within some php code within a foreach() loop. The loop goes through each player and creates a div and draws their image in there. 
There's a database call that returns a 2d array of the weapons that can fire at the enemy(if in range).. 

so the 2D array has up to 3 weapons stored in and here's what really matters

what I need to do is pull the amount of weapons within the 2d array, or count the first dimension of the array - so that I can use this number like foreach(numberOfElementsInFirstDimension)
I'm thinking there might be a way like count all elements and divide by 3(because second dimension has 3 elements per first), but i've had no luck so far finding a solution

I'll upload some code tomorrow, for some reason I can't access my Uni's server from home..
feel free to give me any pointers for the mean time, and sry if someone already posted answer.. I don't even know what to search for[/b]

-----------------------------------
Tony
Thu Nov 19, 2009 1:44 am

RE:traverse 2d array with foreach()
-----------------------------------
foreach doesn't work like that. You don't need the count -- see the docs: 
/* foreach example 4: multi-dimensional arrays */
$a = array();
$a

-----------------------------------
iker
Thu Nov 19, 2009 10:47 am

Re: traverse 2d array with foreach()
-----------------------------------
Hey, thanks for the quick reply

so if i had

$a = array();
$a
as my array thats returned by the database,

foreach ($a as $v1) {
    foreach ($v1 as $v2) {
        echo "$v2\n";
    }
} 

will echo every element.

how would I just pull the names(name1, name2, name3) out of the array without the attack and range?

-----------------------------------
Tony
Thu Nov 19, 2009 12:16 pm

RE:traverse 2d array with foreach()
-----------------------------------
name, att, ran are elements of the array. If you don't want all of them, then don't loop over all of them.

-----------------------------------
iker
Fri Nov 20, 2009 9:39 pm

Re: traverse 2d array with foreach()
-----------------------------------
k, fixed it. thank you tony

i'm using

foreach ($a as $v) {
	echo "$v
and its echoing just the first element like I wanted
