It was hard to wrap my brain around arrays at first, and I still occasionally become perplexed at the best way to structure an array, but you do get used to them.
The easiest type of array to work with is an associative array, where you have a key name and a value:
$student['name'] = "John Smith";
This array is geared towards storing various information about a single student. Since you need to store information about multiple students, you need to add a dimension to the array:
// Manually populate array...
$student[]['name'] = "John Smith";
$student[]['name'] = "Joe Black";
// Cycle through array...
foreach($student as $key => $info)
{
// Display values...
echo $info['$name']."\n";
}
/*
Will display:
John Smith
Joe Black
*/
So what do you do when one piece of information has three different aspects to it? You add another dimension at the end:
// Manually populate array...
$student[1]['name'] = "John Smith";
$student[1]['favorites']['color'] = "green";
$student[1]['favorites']['food'] = "pizza";
$student[1]['favorites']['show'] = "Hell's Kitchen";
$student[2]['name'] = "Joe Black";
$student[2]['favorites']['color'] = "blue";
$student[2]['favorites']['food'] = "cheesecake";
$student[2]['favorites']['show'] = "House";
// Cycle through array...
foreach($student as $key => $info)
{
// Display name part...
echo $info['$name']."\n";
// Cycle through and display "favorites" sub-array...
foreach($info['favorites'] as $key => $value)
echo " Favorite $key: $value\n";
}
/*
Will display:
John Smith
Favorite color: green
Favorite food: pizza
Favorite show: Hell's Kitchen
Joe Black
Favorite color: blue
Favorite food: cheesecake
Favorite show: House
*/
Typically, you'd populate your arrays from a database, of course, but the principal is the same. Usually, I'll try to use the fields from my database as keys just to keep things consistent.
/* POPULATE ARRAY FROM DATABASE */
// Pull names from database...
$name_result = mysql_query("SELECT student_id, name FROM Students");
$x = 1;
// Populate array of names...
while($names = mysql_fetch_assoc($name_result))
{
$student[$x] = $names['name'];
// Pull favorites from database...
$fav_result = mysql_query("SELECT fav_type, fav FROM Favorites WHERE student_id = $student_id");
// Populate array of favorites...
while($favs = mysql_fetch_assoc($fav_result))
{
$fav_type = $favs['fav_type'];
$student[$x][$fav_type] = $favs['fav'];
}
$x++;
}
Does that help?