kreut Posted February 20, 2011 Share Posted February 20, 2011 Hello, I'm generating a list of questions from a database, say $questions. I'd like to number the questions AFTER I load them from the database (I know that I could enter a number associated with them in the database, but it could get tricky, as the questions will continually be updated and deleted). My question, then, is how can a create a new array which associates each question with a number. Thank you! Link to comment https://forums.phpfreaks.com/topic/228236-generating-a-numbered-list-from-a-database/ Share on other sites More sharing options...
Pikachu2000 Posted February 20, 2011 Share Posted February 20, 2011 Just initialize a variable at 1, echo it and increment it with each iteration of the while() loop you use to display the results of the query. Link to comment https://forums.phpfreaks.com/topic/228236-generating-a-numbered-list-from-a-database/#findComment-1176975 Share on other sites More sharing options...
jcbones Posted February 20, 2011 Share Posted February 20, 2011 As Pik suggested: $number = 0; while($row = mysql_fetch_assoc($result)) { echo 'Number: ' . ++$number; } Link to comment https://forums.phpfreaks.com/topic/228236-generating-a-numbered-list-from-a-database/#findComment-1176980 Share on other sites More sharing options...
kreut Posted February 20, 2011 Author Share Posted February 20, 2011 Thanks for the quick responses, but unfortunately I'm actually going to need to refer back to the questions at different times within the page, so I'd like to have some sort of more permanent association (at least while the given web page is active). Any other suggestions would be appreciated. Basically, when I need to print a specific question, say the 17th one, the number 17 should pop up, bearing in mind, that I then may need to refer to, say question 13. Link to comment https://forums.phpfreaks.com/topic/228236-generating-a-numbered-list-from-a-database/#findComment-1176990 Share on other sites More sharing options...
jcbones Posted February 20, 2011 Share Posted February 20, 2011 Well, using the supplied code, I would. $number = 0; while($row = mysql_fetch_assoc($result)) { $storage_array[++$number] = $row['id']; } foreach($storage_array as $number => $questionID) { echo 'Question Number: ' . $number . ' is row ' . $questionID . ' in the database.<br />'; } Link to comment https://forums.phpfreaks.com/topic/228236-generating-a-numbered-list-from-a-database/#findComment-1177036 Share on other sites More sharing options...
kreut Posted February 20, 2011 Author Share Posted February 20, 2011 Thanks! That's just the code that I need. Link to comment https://forums.phpfreaks.com/topic/228236-generating-a-numbered-list-from-a-database/#findComment-1177142 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.