Page 1 of 1
getting values from db and storing in multidimensional array
Posted: Mon Mar 17, 2008 10:14 pm
by thatsme
Hello,
Code: Select all
$q = mysql_query("SELECT member_id, score, first_name, last_name FROM members");
while($r=mysql_fetch_assoc($q))
{
$member_id = $r['member_id'];
$member_det[$member_id][] = $r['score'];
}
The above code works fine. If i want to add first_name, last_name, how should i write and also how to iterate.
Note to moderator:
viewtopic.php?f=1&t=80008. This was my earlier post of similar question. In the earlier post, i was asking building array from forloops and this one is from database. So, please do not think i am posting the same question twice. Thanks
Thanks
Re: getting values from db and storing in multidimensional array
Posted: Mon Mar 17, 2008 10:26 pm
by yacahuma
why are you trying to index the returned values?
You can just
Code: Select all
$arr = array();
while($r=mysql_fetch_assoc($q))
{
$arr[] = $r;
}
foreach($arr as $obj)
{
echo $obj['score'] . $obj['first_name'];
}
Re: getting values from db and storing in multidimensional array
Posted: Tue Mar 18, 2008 12:06 am
by RobertGonzalez
Code: Select all
<?php
$users = array();
$q = mysql_query("SELECT member_id, score, first_name, last_name FROM members");
if ($q) {
while ($r=mysql_fetch_assoc($q)) {
$users[] = $r;
}
}
$usercount = count($users);
if ($usercount) {
for ($i = 0; $i < $usercount; $i++) {
echo '<p>Member id:', $users[$i]['member_id'], '</p>';
echo '<p>Score:', $users[$i]['score'], '</p>';
echo '<p>First Name:', $users[$i]['first_name'], '</p>';
echo '<p>Last Name:', $users[$i]['last_name'], '</p>';
echo '<p>----------</p>';
}
} else {
echo 'There are no users.';
}
?>
Re: getting values from db and storing in multidimensional array
Posted: Tue Mar 18, 2008 12:20 am
by thatsme
Thanks for your replies.
I am indexing because i need values in seperate array. Please see this posting,
viewtopic.php?f=1&t=80008, in which arborint suggestion works fine. In the same way i need to include first_name and last_name as well in that array.
Thanks
Re: getting values from db and storing in multidimensional array
Posted: Tue Mar 18, 2008 1:20 am
by Christopher
I think what you want to do is this. I simplified the code a little more, you don't need the temp variable $member_id. This is a pretty common trick to create an array of database rows where the array keys are the primary keys, I am assuming that this code is doing something different from the previous post that was nested arrays.
Code: Select all
$q = mysql_query("SELECT member_id, score, first_name, last_name FROM members");
while($r=mysql_fetch_assoc($q))
{
$member_det[$r['member_id']] = $r;
}
Re: getting values from db and storing in multidimensional array
Posted: Tue Mar 18, 2008 1:35 am
by thatsme
Your previous suggestion worked fine. I need the similar result here also. One more thing, how to iterate to get first_name and last_name.
Thanks