PHP中的foreach遞歸是循環(huán)語(yǔ)句的一種,它可以通過(guò)遞歸地遍歷多維數(shù)組來(lái)實(shí)現(xiàn)復(fù)雜的操作。基本上說(shuō),foreach遞歸可以幫助我們?cè)诙嗑S數(shù)組中查找特定的值,或者對(duì)數(shù)組的某些元素進(jìn)行修改。
讓我們來(lái)看一個(gè)例子。假設(shè)我們有一個(gè)多維數(shù)組,其中包含了一些圖書(shū)的信息,如書(shū)名、作者、價(jià)格和出版日期。我們想要按出版日期將這些書(shū)分類(lèi),然后計(jì)算每個(gè)分類(lèi)的圖書(shū)總價(jià)值。我們可以用foreach遞歸來(lái)解決這個(gè)問(wèn)題。
$books = array( array("title" =>"Thinking in Java", "author" =>"Bruce Eckel", "price" =>45.00, "date" =>"1998-05-20"), array("title" =>"Programming in Python", "author" =>"Mark Summerfield", "price" =>29.99, "date" =>"2002-03-11"), array("title" =>"Head First PHP & MySQL", "author" =>"Lynn Beighley", "price" =>34.99, "date" =>"2008-01-15"), array("title" =>"Database Design for Mere Mortals", "author" =>"Michael J. Hernandez", "price" =>45.00, "date" =>"2009-06-01"), array("title" =>"Learning PHP, MySQL, & JavaScript", "author" =>"Robin Nixon", "price" =>39.99, "date" =>"2012-03-15"), ); $categories = array(); foreach ($books as $book) { $year = date('Y', strtotime($book['date'])); if (!isset($categories[$year])) { $categories[$year] = array('total' =>0, 'books' =>array()); } $categories[$year]['books'][] = $book; $categories[$year]['total'] += $book['price']; } foreach ($categories as $year =>$category) { echo "Year: $year
"; echo "Total: $".$category['total']."
"; echo "
- ";
foreach ($category['books'] as $book) {
echo "
- ".$book['title']." by ".$book['author']." "; } echo "