-4

我有一个数组

$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);
4

2 回答 2

0

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

于 2013-02-09T11:22:10.480 回答
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
于 2013-02-09T11:54:06.030 回答