Click to See Complete Forum and Search --> : help displaying array elements


moondance
02-11-2004, 11:36 AM
i'm developing a simple class that will return to the user a multidimensional array from a user-defined sql statement.

i'm using the array_fill function, and it seems to be populating it ok, but i'm not sure what loops to use to display it - i want to use the database fields for the key, and the id as the array name, so for instance the following array structure:

$result = array (
"1"=>array(
"Fname"=>"John",
"Sname"=>"Doe",
"DOB"=>"07-02-1970"
)
"2"=>array(
"Fname"=>"Joe",
"Sname"=>"Bloggs",
"DOB"=>"16-10-1990"
)
)

I had used the following code to traverse the array to display each element:

echo "<table border = \"1\" width = \"25%\">";
while (list($key, $item) = each ($result))
{
echo "<tr><td>$key</td><td>$item</td></tr>";
}
echo "<table>";

...but all it says is "Array" for the amount of arrays in it.

Any ideas?
:confused:

YoN
02-11-2004, 12:02 PM
Try this...
echo "<table border = \"1\" width = \"25%\">";
foreach ($result as $val) {
foreach ($val as $skey => $sval) {
echo "<tr><td>$skey</td><td>$sval</td></tr>";
}
}
echo "<table>";

HTH

moondance
02-11-2004, 12:20 PM
hmmm..thats just seems to loop the first element as many times as there are sub-arrays in the results array.

it returned:

0 Joe
Fname Joe
1 Blogs
Sname Blogs
0 Joe
Fname Joe
1 Blogs
Sname Blogs
0 Joe
Fname Joe
1 Blogs
Sname Blogs
0 Joe
Fname Joe
1 Blogs
Sname Blogs

YoN
02-11-2004, 12:52 PM
Use mysql_fetch_assoc() instead of mysql_fetch_array() and try it.
also post the result of print_r($result); to see what your array looks like exaclty.

moondance
02-11-2004, 01:14 PM
yes it seems the way i was populating the array was just filling it up with the first record. I'm using the following statement to populate it:

$numrows = mysql_num_rows($results);

while ($row = mysql_fetch_assoc($results))
{
$returnarray = array_fill(0, $numrows, $row);
}

which i assume is wrong. is the right way to use a for loop, so i can increment the array pointer to the next record?

ps.
the above statement would return the following array of 4 records:
Array ( [0] => Array ( [Fname] => Joe [Sname] => Blogs) [1] => Array ( [Fname] => Joe [Sname] => Blogs ) [2] => Array ( [Fname] => Joe [Sname] => Blogs ) [3] => Array ( [Fname] => Joe [Sname] => Blogs ) )

YoN
02-11-2004, 01:28 PM
I don't understand you well.. Perhaps my english sucks that much that I don't get it. Try this and see if it's what you want; if not, please explain again. ;) $returnarray = array();
while ($row = mysql_fetch_assoc($results))
{
$returnarray[] = $row;
} I edited the code.. You don't need mysql_num_rows() in the code i gave you. :)