Creating associative arrays based on a MySQL query
Posted: Fri Sep 04, 2009 2:30 pm
I'm trying to create some associative arrays based on a MySQL query. I'm getting the right data (can create the individual values from the query), but I can't seem to be able to create the arrays. I've tried working with 'while', with 'foreach', with 'for', but none seem to work. I think I'm missing something in the explanation of how the various PHP functions work that would let me grasp the correct logic.
For each faculty member i, I want to create an array $fac$i with fields: fac_id, fac_name, advStatus (boolean). Then I think I want to combine these into a two-dim array called $fac.
For each faculty member i, I want to create an array $fac$i with fields: fac_id, fac_name, advStatus (boolean). Then I think I want to combine these into a two-dim array called $fac.
Code: Select all
<?php
include("../include.php");
doDB();
//arrays
/*
$fac[fac1] = array("fac_id" => 1, "fac_name" => "Beversluis, Eric", "advStatus" => "False");
echo $fac[fac1]['fac_id']."<br />";
$fac[fac2] = array("fac_id" => 2, "fac_name" =>"Underwood, Lynn", "advStatus" => "True");
echo $fac[fac2]['advStatus']."<br />";
//$fac = array($fac1, $fac2);
echo "<br /><br />";
foreach ($fac as $f) {
while (list($k, $v) = each($f)) {
echo "The ".$k." value is ".$v.".<br />";
}
}
*/
//get list of all faculty
$sqlFacultyList = "Select fac_id,fac_name FROM tblFaculty ORDER BY fac_name";
$resFacultyList = mysqli_query($mysqli, $sqlFacultyList);
$numRows = mysqli_num_rows($resFacultyList);
echo $numRows."<br />"; //gives correct result (4)
//Now I want to create a set of arrays ($fac1, $fac2, etc), which I will then combine into a two-dim array $fac = array($fac1, $fac2,...)
/* Doesnt' work:
while($FacultyList = mysqli_fetch_array($resFacultyList, MYSQLI_ASSOC)) {
$arrName = "$fac".$FacultyList['fac_id'];
$arrName = array(
'fac_id' => $FacultyList['fac_id'],
'fac_name' => $FacultyList['fac_name'],
'advStatus' => "False",
);
}
*/
//The following should work but doesn't want to
for ($i = 0; $i < $numRows; $i++) {
$row = mysqli_fetch_assoc($resFacultyList);
$fac_id = $row['fac_id'];
$fac_name = $row['fac_name'];
$advStatus = "False";
//echo $fac_name; //ie, I've captured the variables correctly.
//I want an array called $fac1 for the first round, $fac2 for the second round etc.
$val = $i+1;
$fac = '$fac'.$val;
echo $fac; //(This give the right value (eg $fac1)
$fac = array('fac_id'=>$fac_id,'fac_name'=>$fac_name,'advStatus'=>$advStatus);
}
echo $fac1['fac_name'];
//This also seems to me should work, but doesn't:
for ($i = 0; $i < $numRows; $i++) {
$val = $i+1;
$fac = '$fac'.$val;
$fac = mysqli_fetch_assoc($resFacultyList);
}
echo "<br />End";
mysqli_free_result($resID);
msqli_close($mysqli);
?>