我建議先做所有的處理,然後只使用foreach()
來顯示它。
第一步是檢查需要進行哪種修改來準備$show_listingsRecords
陣列。
- 如果沒有子陣列,那麼您將需要使用全部三個
$alternates
子陣列。
- 如果子陣列的數量沒有均勻分配
$chunk_size
(每批次子陣列的數量),則只合並$alternates
的必要數量的子陣列以完成「批量」。
代碼:(Demo)
$show_listingsRecords=array(
array("name"=>1,"description"=>2,"link"=>3),
array("name"=>4,"description"=>5,"link"=>6),
array("name"=>7,"description"=>8,"link"=>9),
array("name"=>10,"description"=>11,"link"=>12),
array("name"=>13,"description"=>14,"link"=>15)
);
$alternates=array(
array("name"=>"backup1A","description"=>"backup1B","link"=>"backup1C"),
array("name"=>"backup2A","description"=>"backup2B","link"=>"backup2C"),
array("name"=>"backup3A","description"=>"backup3B","link"=>"backup3C") // needed if no listings at all
);
$chunk_size=3; // 3 is used in this case
// conditionally prepare array
if(!$size=sizeof($show_listingsRecords)){ // if no listings at all (empty array)
$show_listingsRecords=$alternates;
}elseif($over=$size%$chunk_size){ // $over is how many extra elements beyond "even" (0,1,2 in this case)
$show_listingsRecords=array_merge($show_listingsRecords,array_slice($alternates,0,$chunk_size-$over));
}
// display
foreach(array_chunk($show_listingsRecords,$chunk_size) as $batch){ // iterate in batches
echo "<div>\n";
foreach($batch as $listing){ // iterate the arrays in the batch
echo "\t<div>",implode(' + ',$listing),"</div>\n";
}
echo "</div>\n";
}
輸出:
<div>
<div>1 + 2 + 3</div>
<div>4 + 5 + 6</div>
<div>7 + 8 + 9</div>
</div>
<div>
<div>10 + 11 + 12</div>
<div>13 + 14 + 15</div>
<div>backup1A + backup1B + backup1C</div>
</div>
你需要把更多的細節,明白了,你在找什麼來實現的。放置圖像會更好。 –