galvin Posted January 14, 2011 Share Posted January 14, 2011 I have this simple code below to pull back info from a mysql database and create an array. I have two questions... 1. The items in this array will automatically have indexes of [0] and [1] and [2] and so on. If I wanted the first index to be [1] instead of [0], how could I do that? In other words, I want the first item in the array to have an index of [1] (like regular counting) rather than [0] (programming counting). 2. Each 'answer' actually has its own 'answerid' in the database, which I am bringing back as well with the query. If I wanted those answerids to be the indexes, how would I adjust the code below? $sql = "SELECT answer, answerid FROM answers WHERE quizid = $quizid"; $createanswerarray = mysql_query($sql, $connection); if (!$createanswerarray) { die("Database query failed: " . mysql_error()); } else { $_SESSION['answers']=mysql_fetch_array($createanswerarray); } } else { } Link to comment https://forums.phpfreaks.com/topic/224380-two-questions-about-array-indexes/ Share on other sites More sharing options...
btherl Posted January 14, 2011 Share Posted January 14, 2011 For both of those, you will need to renumber your array. To set the answerid as the index I would recommend you create a new array rather than renumbering, so you don't accidentally clobber something if you have low answerids that match the old array indexes. Link to comment https://forums.phpfreaks.com/topic/224380-two-questions-about-array-indexes/#findComment-1159205 Share on other sites More sharing options...
BlueSkyIS Posted January 14, 2011 Share Posted January 14, 2011 1. don't do that. always know that the first element of an array is key 0. if you need to display 1 for 0, add +1 to the key. but don't change the key; keep consistency. 2. create a new array. loop over the query results, assigning $newarray[$answerid] = $answer for each record Link to comment https://forums.phpfreaks.com/topic/224380-two-questions-about-array-indexes/#findComment-1159207 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.