PHP:将数组拆分为更深的数组

时间:2010-03-31 13:48:10

标签: php arrays foreach

我有以下数组:

Array(
   [0] => 0,0
   [1] => 0,1
   [2] => 0,2
   [3] => 0,3
   [4] => 1,0
   [5] => 1,1
   [6] => 1,2
   [7] => 2,0
   [8] => 2,1
   [9] => 2,2
   [10] => 2,3 
)

我想把它分成以下结构:

Array( 

[0] => Array (
        [0] => 0
        [1] => 1
        [2] => 2
        [3] => 3
    )
[1] => Array (
        [0] => 0
        [1] => 1
        [2] => 2
        [3] => 3
    )
[2] => Array (
        [0] => 0
        [1] => 1
        [2] => 2
        [3] => 3
    )
[3] => Array (
        [0] => 0
        [1] => 1
        [2] => 2
        [3] => 3 
)

,即,在“X,Y”值中,X对应于新数组中值“Y”的位置。我似乎无法理解逻辑,这是我第一次以这种方式使用'foreach'。

非常感谢任何帮助,指出我正确的方向。

1 个答案:

答案 0 :(得分:6)

示例中的输入和输出数组并不完全匹配,但我猜你正在寻找这个:

$array = array(…as above…);
$newArray = array();

foreach ($array as $value) {
    list($x, $y) = explode(',', $value);
    $newArray[$x][] = $y;
}