好的,我有一个问题。我想设置一个新闻源,这将显示用户在收到订单时收到的问题和评论。我设置了一个功能来完成所有这些。我再次不知道它是否最有效但我只想让它发挥作用。所以这就是我所拥有的
public function foo ()
{
//Retrieve all of the questions
$Statement = $this->Database->prepare("SELECT * FROM table WHERE condition = ?");
$Statement->execute(array($this->variable));
while ($row = $Statement->fetch(PDO::FETCH_ASSOC))
{
$id[] = $row["id"];
$question[] = $row["question"];
$asker[] = $row["asker"];
$timestamp[] = $row["timestamp"];
$likes[] = $row["likes"];
}
$iLimit = count($id); //Set a limit based on the size of the array
if ($iLimit > 0)
{
//Save everything in an array for the questions
for ($iCount = 0; $iCount < $iLimit; $iCount++)
{
$question[$iCount] = Array ( "id" => $id[$iCount],
"text" => $question[$iCount],
"username" => $asker[$iCount],
"timestamp" => $timestamp[$iCount],
"likes" => $likes[$iCount] );
}
}
//Retrieve all of the comments
$Statement = $this->Database->prepare("SELECT * FROM table WHERE condition = ?");
$Statement->execute(array($this->variable));
while ($row = $Statement->fetch(PDO::FETCH_ASSOC))
{
$id[] = $row["id"];
$comment[] = $row["comment"];
$commenter[] = $row["commenter"];
$timestamp[] = $row["timestamp"];
$likes[] = $row["likes"];
}
$iLimit = count($id); //Set a limit based on the size of the array
if ($iLimit > 0)
{
//Save everything in an array for comments
for ($iCount = 0; $iCount < $iLimit; $iCount++)
{
$comment[$iCount] = Array ( "id" => $id[$iCount],
"text" => $comment[$iCount],
"username" => $commenter[$iCount],
"timestamp" => $timestamp[$iCount],
"likes" => $likes[$iCount] );
}
}
//Merge the two arrays
$aNewsFeed = array_merge($question, $comment);
foreach ($aNewsFeed as $row)
{
$aOrdered[] = $row["timestamp"];
}
array_multisort($aOrdered, SORT_DESC, $aNewsFeed); //Sort the array
return $aNewsFeed;
} //end getNewsFeed
然后我使用foreach循环调用它
foreach ($Class->foo() as $news)
{
echo $news["text"]
}
但每次它总是给出foreach循环的两个额外的空白贯穿。或者我不知道它是否实际上是数组的一部分,因为如果它是foreach循环的问题,它通常会发出错误。我认为它必须是array_merge()函数的问题,但我不完全确定。有什么想法吗?
感谢您的帮助。对此,我真的非常感激。
答案 0 :(得分:0)
您似乎正在使用数组$id
,$likes
等作为临时变量,但在第二次使用它们之前您没有重置它们,因此您的$id
数组将具有当你开始将它用于评论时,问题就在其中。
在您(重新)使用它们之前,您应该始终初始化数组:
$id = array();
// first loop
$id = array();
// second loop
答案 1 :(得分:0)
foreach ($Class->foo() as $news)
{
if($news["text"]!=""){
echo $news["text"];
}
}