本文介紹了php foreach 為key,每兩個數字為一組的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
<?php
$data=array('1','2','3','4','5','6','7','8','9','10','11');
foreach($data as $key=> $element){
if($key % 2 != 0){
echo $element.'<br />';
}
echo '<hr />';
}
?>
php foreach 作為key,如何讓每兩個數字為一組?
php foreach as key, how to make every two number as a group?
我要輸出:
1,2
_____
3,4
_____
5,6
_____
7,8
_____
9,10
_____
11
推薦答案
查看 array_chunk()
函數.
Have a look at the array_chunk()
function.
在你的情況下,你會像這樣使用它:
In your case you'd use it like this:
foreach(array_chunk($data, 2) as $values) {
echo implode(',', $values)."
";
}
在最后一次迭代中 $values
將只有一個元素,所以如果你打算使用它們的索引直接訪問元素,請記住使用 count()
來檢查數組的元素計數.
During the last iteration $values
will have only one element so if you plan to access the elements directly using their index remember to use count()
to check the array's element count.
這篇關于php foreach 為key,每兩個數字為一組的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!