来自现有的新数组

时间:2013-02-09 11:08:38

标签: php

我有一个数组

$t1 = array(2,1,8,18,10);

我想使用定义的键

从这个创建新的数组
$t11 = array("no" => 2, "to" => 1);
$t12 = array("no" => 1, "to" => 8);
$t13 = array("no" => 8, "to" => 18);
$t14 = array("no" => 18, "to" => 10);
$t15 = array("no" => 10, "to" => 0);

2 个答案:

答案 0 :(得分:0)

使用带有计数器变量的循环,例如$ i,使用$ t1 [$ i]和$ t1 [$ i + 1]制作新数组,增加$ i,然后重复。

答案 1 :(得分:0)

您可以使用CachingIteratorextract

$a = array(2,1,8,18,10);
$it = new CachingIterator(new ArrayIterator($a));
$t1 = array();
foreach ( $it as $v ) {
    $var = array("no" => $v,"to" => 0);
    if ($it->hasNext()) {
        $var["to"] = $it->getInnerIterator()->current();
    }
    $t1[] = $var;

}

extract($t1, EXTR_PREFIX_ALL, "t1");
var_dump($t1_0,$t1_1,$t1_2,$t1_3,$t1_4);

输出

array (size=2)
  'no' => int 2
  'to' => int 1
array (size=2)
  'no' => int 1
  'to' => int 8
array (size=2)
  'no' => int 8
  'to' => int 18
array (size=2)
  'no' => int 18
  'to' => int 10
array (size=2)
  'no' => int 10
  'to' => int 0