I am having some difficulty converting some MySQL Results to a PHP Array.
Displaying the results of my news items are easy.
$news = mysql_fetch_assoc($rs_items); // rs_items is already the result of a MySQL query
echo $news[‘id’]; Displays the database id
echo $news[‘title’]; Displays the title
echo $news[‘active’]; Displays the 0/1 value of active/inactive
Let’s say I have 10 news items, ID’s 1 - 10, 10 different titles, etc…
What I need to do, is convert the $news[‘id’] into a PHP Array.
Here is what I am trying,:
foreach ($news[‘id’] as $value)
{
$results = $value;
}
print_r ($results);
I was hoping to see the ID numbers:
[0] => 1
[1] => 2
[2] => 3 etc… etc…
But this is not giving me any results at all. What am I doing wrong?
You should be running mysql_fetch_assoc in a loop, something like:
while($news = mysql_fetch_assoc($rs_items)){
echo $news['id']; //Displays the database id
echo $news['title']; //Displays the title
echo $news['active']; //Displays the 0/1 value of active/inactive
}
So to collect ids you’d just add:
while($news = mysql_fetch_assoc($rs_items)){
echo $news['id']; //Displays the database id
echo $news['title']; //Displays the title
echo $news['active']; //Displays the 0/1 value of active/inactive
$results[] = $news['id'];
}
Thanks for the response. I completely forgot about the post after coming up with a solution of my own.
FYI: I was doing exactly what you suggested, however I was trying to use a “foreach” loop instead of a “while” loop. As soon as I tried a “while” loop (like you suggest in your 2nd step) it worked perfectly.