好吧,以及我有一個問題。我想設置一個新聞源,這將顯示這兩個問題,以及用戶收到的評論。我設立了一個功能來完成所有這些。我不知道它是否是最高效的,但我只是想讓它工作。所以這是我問題與我的陣列
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()函數的問題,但我不完全確定。有任何想法嗎?
謝謝你的幫助。對此,我真的非常感激。
明顯的問題要問你的自我我想被你明白['array_merge']之間的差值(HTTP ://php.net/manual/en/function.array-merge.php)和'$ array1 + $ array2'? – ficuscr