I'll break it down as simple as possible then post all the necessary code.
Goal: to get all answers for each sub period in a period for all the users, and the ones that don't have one i will mark the cells (don't worry about this part) so i can perform data extrapolation on it later.
User class: User has an Id and a list of periods
Period class: Period has an Id and a list of sub periods
Sub Period class: Sub Period has an Id and a list of questions
Question class: Each question has answer
Now the code, the commented lines in the first couple of nested loops is the key to figure out first. The 2nd line in each instance is my attempt so far. With both those second lines un-commented i get an error on this line:
$user->periods[$period]->addSubPeriod($period->periodId, $subPeriod);
saying: Notice: Undefined offset: 1 and Fatal error: Call to a member function addSubPeriod() on a non-object
$periods_arr = array(1, 2, 3, 4, 5);
$subPeriods_arr = array(1, 2);
$questionslist = array("q_1_1", "q_1_2", "q_2_1", "q_2_2", "q_3_1", "q_4_1", "q_5_1");
class User {
public $userId;
public $periods = array();
public function __construct($number) {
$this->userId = $number;
}
public function addPeriod($id, $pno)
{
$this->periods[$id] = new Period($pno);
}
}
class Period {
public $periodId;
public $subPeriods = array();
public function __construct($number)
{
$this->periodId = $number;
}
public function addSubPeriod($id, $spno)
{
$this->subPeriods[$id] = new SubPeriod($spno);
}
}
class SubPeriod {
public $subPeriodId;
public $answers = array();
public function __construct($number)
{
$this->subPeriodId = $number;
}
public function addAnswer($id, $answer)
{
$this->answers[$id] = new Question($answer);
}
}
class Question {
public $answer;
public function __construct($ans)
{
$this->answer = $ans;
}
public function getAnswer()
{
echo $this->answer;
}
}
$userlist = array();
$sql = 'SELECT user_ref FROM _survey_1_as GROUP BY user_ref ORDER BY user_ref ASC';
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
array_push($userlist, new User($row['user_ref']));
}
foreach ($userlist as &$user)
{
foreach ($periods_arr as &$period)
{
// set the current users ($user) period
// $user->addPeriod($user->userId, $period);
foreach ($subPeriods_arr as &$subPeriod)
{
// set the sub_period for the current users period
// $user->periods[$period]->addSubPeriod($period->periodId, $subPeriod);
foreach($questionslist as &$aquestion)
{
$sql = 'SELECT ' . $aquestion . ' FROM _survey_1_as WHERE user_ref = ' .
$user->userId . ' AND answer_period = ' . $period . ' AND answer_sub_period = ' .
$subPeriod .'';
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
$user->periods[$period]->subPeriods[$subPeriod]->addAnswer($row[$aquestion]);
}
}
}
}
}