如何在每次循环中显示for each循环中的两个元素?
例如,我有这样的一个数组:
$arr = array('a', 'b', 'c', 'd','e','f');
而且想要像这样展示记录:
a-b
c-d
e-f
有什么想法吗?
你可以使用array_chunk
,它正是为这种情况而设计的,是最短且最有效的方法。
$arr = array('a', 'b', 'c', 'd','e','f');
foreach(array_chunk($arr , 2) as $val) {
echo implode('-', $val)."\n";
}
将数组分割成指定大小的子数组。
使用for
循环遍历数组。
在每次迭代中,按计数器打印当前值和当前值加一的值。
递增计数器。
<?php
$arr = array('a', 'b', 'c', 'd','e','f');
$i=0;
$len = count($arr);
for ($i=0; $i< $len; $i++) { // We could have used count($arr)
//instead of $len. But, it will lead to
//multiple calls to count() function causing code run slowly.
echo "<br/>".$arr[$i] . '-' . $arr[$i+1];
++$i;
}
?>
$len%2 = 1
,使用这个解决方案将会出现 Undefined offset: <faulty_offset_number>
的错误。 - dickwan$i++
),可能会令人困惑。最好每次将$i
增加两个例如 for ($i=0; $i< $len; $i += 2)
。尽管未定义的偏移错误仍然存在问题。 - John Ellmore<?php
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
?>
Array
(
[0] => Array
(
[0] => a
[1] => b
)
[1] => Array
(
[0] => c
[1] => d
)
[2] => Array
(
[0] => e
)
)
试试这个:
<?php
$array = array('a', 'b', 'c', 'd','e','f');
$length = count($array);
for ($i=0; $i< $length; $i+2) {
echo "<br/>".$arr[$i] . '-' . $arr[$i+1];
}
?>