如何在php中循环中设置每个2的值

时间:2017-06-02 05:47:09

标签: php loops

The loop returns like this
value 1
value 2
value 3
value 4
value 5
value 6
value 7
value 8
value 9
value 10


The following should be my output

------------------------------
    value 1
1
    value 2
------------------------------
    value 3
2   
    value 4
-------------------------------
    value 5
3   
    value 6
-------------------------------
    value 7
4       
    value 8
-------------------------------
    value 9
5       
    value 10
--------------------------------    

任何人都可以帮助我在网上搜索更多参考资料。

2 个答案:

答案 0 :(得分:1)

你可以循环遍历你的数组并采取两个:

$test = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];

for($i = 0; $i < count($test); $i += 2) {
  $j = $i + 1;
  echo "$test[$i] \n"; 
  echo "$test[$j] \n";
}

答案 1 :(得分:1)

您可以使用如下所示的array_chunk():

$cars=array("Volvo","BMW","Toyota","Honda","Mercedes","Opel");
echo "<pre>"; print_r(array_chunk($cars,2));

输出:

Array
(
    [0] => Array
        (
            [0] => Volvo
            [1] => BMW
        )

    [1] => Array
        (
            [0] => Toyota
            [1] => Honda
        )

    [2] => Array
        (
            [0] => Mercedes
            [1] => Opel
        )

)