Page 1 of 2
2-dimensional array in PHP?
Posted: Wed Jan 13, 2010 9:00 pm
by OldRod
I have a base_stats table that has a row for each race with 5 fields for each record. I'm wanting to read that into a 2-dimensional array in PHP so I can do some manipulation with it before using it, but I'm not having any luck.
Anyone got an example that shows how to do this?
Re: 2-dimensional array in PHP?
Posted: Wed Jan 13, 2010 9:34 pm
by Chris
Code: Select all
<?php
$array = array( array('foo', 'bar') );
foreach( $array as $array2 )
{
foreach( $array2 as $array2value )
{
echo $array2value; //foobar
}
}
?>
Something like that?
Re: 2-dimensional array in PHP?
Posted: Wed Jan 13, 2010 10:29 pm
by Jackolantern
PHP does not natively support two-dimensional arrays like C++ does (like foo[2,1]), but does support "array or arrays" (like $foo[2][1]).
Re: 2-dimensional array in PHP?
Posted: Wed Jan 13, 2010 11:33 pm
by OldRod
I've got the table read in ok, using this code:
Code: Select all
$qrystring = "SELECT * FROM $db_race_table";
$result = mysql_query ($qrystring) or die("Could not select from table:$db_race_table");
$ktr = 0;
while ($race_row = mysql_fetch_assoc($result))
{
foreach ($race_row as $key=>$value)
{
$race_stats[$ktr][$key] = $value;
}
$ktr++;
}
Now I just need to know how to reference it.
How do I reference the 2nd field in the 3rd record, for example?
My c++ past tells me $race_stats[3][2] should work, but it doesn't

Re: 2-dimensional array in PHP?
Posted: Wed Jan 13, 2010 11:54 pm
by Jackolantern
Remember that arrays are 0 based
Re: 2-dimensional array in PHP?
Posted: Wed Jan 13, 2010 11:56 pm
by hallsofvallhalla
yes it starts at 0
[0,1]
Re: 2-dimensional array in PHP?
Posted: Thu Jan 14, 2010 12:14 am
by OldRod
This:
echo "$race_stats[1][0]";
echo "$race_stats[1][1]";
displays the following:
Array[0]
Array[1]
Re: 2-dimensional array in PHP?
Posted: Thu Jan 14, 2010 1:39 am
by hallsofvallhalla
i am not seeing where you defined $race_stats as an array
$array_stats = array(value,value,value) ect
Re: 2-dimensional array in PHP?
Posted: Thu Jan 14, 2010 1:42 am
by OldRod
I have:
$race_stats=array();
at the top of the file - I just didn't get it in when I copied/pasted the code, sorry
I'm thinking of going a different route to accomplish this - this is getting too frustrating

Re: 2-dimensional array in PHP?
Posted: Thu Jan 14, 2010 2:31 am
by Jackolantern
I could be wrong, but because PHP is a weakly typed language, I am not sure that typing
will make it an array. Also, to make an array of an array, wouldn't it have to be
?
However, I am not sure if it can be done like that. Later in the code, did you treat it like an array, where you would fill it like
?