PHP:通过索引将3个数组合并为一个多维数组

时间:2014-05-23 15:55:43

标签: php arrays multidimensional-array

我从PHP开始,而这就是我坚持阵列融合难题的那一刻。

我有3个阵列:

t1 Array
(
    [0] => I
    [1] => You
    [2] => She

)


t2 Array
(
    [0] => am
    [1] => are
    [2] => is

)


t3 Array
(
    [0] => confused
    [1] => great
    [2] => awesome

)

我想以一种方式合并它们,结果如下:

$result = array (
        array( 'I', 'am', 'confused' ),
        array( 'You', 'are', 'great' ),
        array( 'She', 'is', 'awesome' ),
);

问题是每个数组(t1,t2,t3)可以完成不同数量的值(数据来自上传的文件)。 确保每次t1,t2和t3的值都相等。我只是无法弄清楚如何做到这一点。你能给我一个提示吗?

2 个答案:

答案 0 :(得分:2)

演示SPL的MultipleIterator

$t1 = array( 'I', 'You', 'She' );
$t2 = array( 'am', 'are', 'is' );
$t3 = array( 'confused', 'great', 'awesome' );

$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($t1));
$mi->attachIterator(new ArrayIterator($t2));
$mi->attachIterator(new ArrayIterator($t3));
$newArray = array();
foreach($mi as $details) {
    $newArray[] = $details;
}
var_dump($newArray);

答案 1 :(得分:0)

或使用while循环:

$array1 = ["I","You","She"];
$array2 = ["am","are","is"];
$array3 = ["confused","great","awesome"];

$i=0;

while ( $i < 3 ) {
    $result[$i] = [$array1[$i],$array2[$i],$array3[$i]];
    $i++;   
}