如何在某一点停止foreach,因此不会抛出未定义的错误

时间:2014-12-16 15:00:41

标签: php html arrays loops associative-array

目前我有一个像这样的数组:

Array ( [0] => Array ( 
[username] => Humza 
[Reputation] => -50 
[Question_Title] => Will 
[Question] => Yes Ofc 
[Rating] => 101 
[Category] => Programming
[num_answers] => 0 ) 

[1] => Array ( 
[username] => Humza 
[Reputation] => -50 
[Question_Title] => This will not have an answer 
[Question] => This does not derserve an Answer 
[Rating] => -100
[Category] => Programming 
[num_answers] => 2 ) 

[2] => Array ( 
[AnswerUserName] => Humza 
[Answer] => Yup? 
[Answer_Rating] => 909 
[Reputation] => -50 )

[3] => Array ( 
[AnswerUserName] => God 
[Answer] => Wohoo 
[Answer_Rating] => 15
[Reputation] => 9999 ) )

我正在使用foreach循环来显示它:

foreach($Quest as $Value)
{
  echo '<font size="3">',"<b>Username: </b>", $Value['username'],"&nbsp;","&nbsp;",
  "<b>User Reputation: </b>",$Value['Reputation'],"&nbsp;","&nbsp;",
  "<b>Question Rating:</b>",$Value['Rating'],"&nbsp;","&nbsp;",'</font>',
  "<b>Category: </b>",$Value['Category'],"&nbsp;","&nbsp;",
  "<b>Number Of Answers Available:  </b>",$Value['num_answers'];
}

最终这将开始打印'错误:未定义索引'我知道它为什么会发生但我想知道如何阻止它,以便我可以开始显示数组的答案部分。

非常感谢任何帮助 谢谢,提前。

1 个答案:

答案 0 :(得分:3)

为什么不基于子数组值echo而不是在特定点停止循环?存在?

foreach($Quest as $Value)
{
  echo '<font size="3">'; // No one uses <font> anymore by the way
  if (isset($Value['username'])) echo "<b>Username: </b>", $Value['username'],"&nbsp;","&nbsp;";
  if (isset($Value['Reputation'])) echo "<b>User Reputation: </b>",$Value['Reputation'],"&nbsp;","&nbsp;";
  if (isset($Value['Rating'])) echo "<b>Question Rating:</b>",$Value['Rating'],"&nbsp;","&nbsp;",'</font>';
  if (isset($Value['Category'])) echo "<b>Category: </b>",$Value['Category'],"&nbsp;","&nbsp;";
  if (isset($Value['num_answers'])) echo "<b>Number Of Answers Available:  </b>",$Value['num_answers'];
}