...

View Full Version : referencing array data



homerUK
09-03-2007, 05:16 PM
Hey,

I've got an array which I've made up with data from the database. It's looking like this at the moment:



$staff_array[$staffID] = $db_row['staff_id'];


how would I then loop through the contents of the staff array?? I normally use something like



for ($x=0;$x<sizeof($staff_array);$x++) {
echo "This staff = " . $staff_array[$x] . "<br />";
}


the above won't send anything out, as the staff numbers in the array are set up like "A332012" and "A332673". How can I reference the actual name of the array element?? I also have other elements within that array like the name, age etc.

thanks for any help!

Mwnciau
09-03-2007, 06:10 PM
foreach($staff_array as $staff){
echo "This staff = " . $staff . "<br />";
}

homerUK
09-03-2007, 07:06 PM
yeah that's the sort of thing - maybe I should be clearer about what's in the array!! I was cutting the code down so that I could try and get a quick answer..





while ($row = mysql_fetch_array($result) {
$years_array = array("2003" => $row['2003'], "2004" => $row['2004'], "2005" => $row['2005']);
$staff_array[$row['staff_id'] = $years_array;
}


so the above would create an array like



array(
"A118221" =>
array(
"2003" => 221,
"2004" => 215,
"2005" => 227
),
"A118226" =>
array(
"2003" => 212,
"2004" => 288,
"2005" => 221
)
)


so the actual array is named the staff ID, and it has a nested array inside it. All I need to do is loop through the whole staff array listing the staff ID then each "year" within it. Sorry if this isn't clear!!

Mwnciau
09-03-2007, 08:15 PM
foreach($staff_array as $k1 => $v1){
echo "This staff = " . $k1 . "<br />";
foreach ($v1 as $k2 => $year){
echo ' Year '.$k2.': '.$year.'<br />';
}
echo '<br />';
}

Is that what you wanted?

homerUK
09-04-2007, 11:13 AM
worked perfectly!! thanks!! :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum