从平面数组创建双元素行,其中每隔一行的值也是下一行的第一个值

Create 2-element rows from flat array where the every second row value is also the first value of the next row

$arrayinput = array("a", "b", "c", "d", "e");

如何实现以下输出....

输出:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

[1] => Array
    (
        [0] => b
        [1] => c
    )

[2] => Array
    (
        [0] => c
        [1] => d
    )

[3] => Array
    (
        [0] => d
        [1] => e
    )

[4] => Array
    (
        [0] => e
    )

)

你可以使用这个,live demo here

<?php
$arrayinput = array("a","b","c","d","e");

$array = [];
foreach($arrayinput as $v)
{
  $arr = [];
  $arr[] = $v;
  if($next = next($arrayinput))
    $arr[] = $next;
  $array[] = $arr;
}
print_r($array);

现场示例:http://sandbox.onlinephpfunctions.com/code/4de9dda457de92abdee6b4aec83b3ccff680334e

$arrayinput = array("a","b","c","d","e");
$result = [];

for ($x = 0; $x < count($arrayinput); $x+=2 ) {
    $tmp = [];
    $tmp[] = $arrayinput[$x];
    if ($x+1 < count($arrayinput)) $tmp[] = $arrayinput[$x+1];
    $result[] = $tmp;
}

var_dump($result);

通过声明一次性引用变量,您不需要调用 next() -- 这不是错误安全的并且在 php manual 中有警告。您也不需要跟踪以前的索引或重复调用 count().

对于除第一次之外的所有迭代(因为没有前一个值),将当前值作为第二个元素推入前一个子数组。推送第二个值后,“断开”参考变量,以便可以在后续迭代中重复相同的过程。这就是我在自己的项目中的做法。

代码:(Demo)

$result = [];
foreach (range('a', 'e') as $value) {
    if ($result) {
        $row[] = $value;
        unset($row);
    }
    $row = [$value];
    $result[] = &$row;
}
var_export($result);

如果你总是想在每个子数组中有 2 个元素并且你想在最后一次迭代中用 null 填充,你可以使用转置技术并发送输入数组的副本(减去第一个元素)作为附加参数。这是一种更简洁的技术(单行)(Demo)

var_export(array_map(null, $array, array_slice($array, 1)));