在第二个foreach循环中,此行上出现非法偏移类型错误。
$userlist[$user]->addPeriod($period);
根据过去线程中提供的过去信息进行了一些更改,这是代码的新版本。还有一个警告但我认为如果错误得到解决可能会解决:
在非对象
上调用成员函数addPeriod()
$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($pno)
{
$this->periods[] = new Period($pno);
}
}
class Period {
public $periodNo;
public $subPeriods = array();
public function __construct($number)
{
$this->periodNo = $number;
}
public function addSubPeriod($spno)
{
$this->subPeriods[] = new SubPeriod($spno);
}
}
class SubPeriod {
public $SubPeriodNo;
public $answers = array();
public function __construct($number)
{
$this->SubPeriodNo = $number;
}
public function addAnswer($answer)
{
$this->answers[] = new Question($answer);
}
}
class Question {
public $answer;
public function __construct($ans)
{
$this->answer = $ans;
}
public function getAnswer()
{
echo $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))
{
$userlist[] = new User($row['user_ref']);
}
foreach ($userlist as &$user)
{
foreach ($periods_arr as &$period)
{
$userlist[$user]->addPeriod($period);
foreach ($subPeriods_arr as &$subPeriod)
{
$userlist[$user]->periods[$period]->addSubPeriod($subPeriod);
foreach($questionslist as &$aquestion)
{
$sql = 'SELECT ' . $aquestion . ' FROM _survey_1_as WHERE user_ref = ' .
$user . ' AND answer_sub_period = ' . $subPeriod . ' AND answer_period = ' . $period .'';
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
$userlist[$user]->periods[$period]->subPeriods[$subPeriod]->addAnswer($row[$questionNumber]);
}
}
}
}
}
$userlist[3]->periods[3]->subPeriods[1]->getAnswer();
答案 0 :(得分:1)
您使用$user
作为$userlist
数组的键,但您将其作为值获取。尝试这样的事情:
foreach ($userlist as $user => $userVal)
{
...
$userlist[$user]->addPeriod($period);
}
这会使$user
成为$userlist
数组的密钥。
做这样的事情会更清楚:
foreach ($userlist as $user)
{
}
然后不要将$user
用作数组中的键,而只需使用$user
作为值。例如:
$user->addPeriod($period);
...
$user->periods[$period]->addSubPeriod($subPeriod);