我正在尝试执行此代码,但我得到了#34;为foreach()"提供的无效参数。我无法理解为什么。
$team = array(); //The team array consist all the teams that have occured so far in the loop and is empty from the beginning
if (mysql_num_rows($select_projects) > 0) {
while($ROW = mysql_fetch_array($select_projects)) {
//If there is a team assigned to the object that have not occurred before,
//create a tr with the teamname as id,
//otherwise create a tr with id No team.
if($ROW['Team'] !== "" && (in_array($ROW['Team'], $team) == False)){
echo '<tr id="'.$ROW['Team'].'"> <td>'.$ROW['Team'].'</td>';
foreach($ROW['PlannedSprint'] as $plannedsprint){
if ($plannedsprint == "541"){
echo '<td>'.$ROW[DatabaseID].'';
}
}
echo '</td></tr>';
array_push($team, $ROW['Team']);
}
else if($ROW['Team'] == "" && (in_array($ROW['Team'], $team) == False)){
echo '<tr id="no_team"> <td>No team</td></tr>';
array_push($team, $ROW['Team']);
}
}
}
答案 0 :(得分:0)
您应该考虑一下数据库设计。我猜你试图在团队和他们计划的冲刺之间达到one-to-many-relationship。 请考虑以下表格:
Teams:
------------
|ID|Name |...
|1 |teamOne |...
|2 |teamTwo |...
Sprints:
------------
|ID|Name|byTeam|...
|1 |foo |1 |...
|2 |bar |2 |...
|3 |baz |2 |...
|4 |toDo|NULL |...
这是正确的方法,因为 a)只存储必要的信息(如果一个团队进行了42次会话,将团队名称存储42次是没有用的!) b)它避免了更新异常。 (如果更改团队名称,则需要更改当前模型中的每个sprint-row) c)您可以轻松添加/删除列
使用此数据库,您的代码可能是:(使用漂亮的PDO-Feature:)
$db = new PDO('mysql:host=localhost;dbname=workplan', 'mysqlUser', 'mysqlPassw');
$mainQuery = $db->query('SELECT COALESCE(Team.Name,\'No Team\') as teamName, Sprints.Name as taskName, Sprints.ID as taskID FROM Sprints LEFT JOIN Teams ON Sprints.byTeam = Teams.ID ORDER BY Teams.ID');
$resultToShow = $mainQuery->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_GROUP);
/*fetch_group will combine all rows with the same value for the _first column_ in an associative array. Therefore, the array will now look the following:
Array(
['No Team']=> Array(
Array(
['taskName']=> 'ToDo',
['taskID']=> 4
),
),
['teamOne']=> Array(
Array(
['taskName']=>'foo',
['taskId']=>1
)
),
['teamTwo']=> Array(
Array(
['taskName']=>'Bar',
['taskId']=>2
),
Array(
['taskName']=>'Baz',
['taskId']=>3
)
)
)
*/
foreach($resultToShow as $teamName => $sprints) {
/*if you really want to show every sprint as a _column_, use the following lines:
echo '<tr id=' . $teamName . '><td>' . $teamName . '</td>';
foreach($sprints as $sprint){
echo '<td>'.$sprint['taskID'].'</td>';
}
echo '</tr>';
*/
//But i think you more want a grouped table, so you could use:
echo '<tr class=' . $teamName . '><td colspan=2>' . $teamName . '</td>';
foreach($sprints as $sprint){
echo '<tr><td>'.$sprint['taskID'].'</td><td>'.$sprint['taskName'].'</td></tr>';
}
}
我真的希望这会对你有所帮助,如果没有,请不要犹豫。 我建议你阅读一些关于实体关系模型,关系和SQL连接的内容。他们将在未来帮助您了解数据库并设计复杂和高质量的数据库应用程序: - )