将平面数据表转换为多维数组

时间:2012-01-09 17:42:28

标签: php recursion multidimensional-array

我有这些数据(列是深度,名称,值,顺序是正确的):

0, id,    12
0, name,  Name
0, pages,
1, 0,     Page 1
1, 1,     Page 2
1, 2,     Page 3
0, items,
1, 0,
2, id,    4
2, title, Example Items

我正在尝试从中生成这样的数组结构:

Array
(
    [id] => 12
    [name] => Name
    [pages] => Array
        (
            [0] => Page 1
            [1] => Page 1
            [2] => Page 1
        )
    [items] => Array
        (
            [0] => Array
                (
                    [id] => 4
                    [title] => Example Item
                )
        )
)

到目前为止我尝试过的每一次尝试都失败了,我似乎无法理解逻辑。任何帮助,将不胜感激。感谢。

1 个答案:

答案 0 :(得分:3)

你可以通过一些参考技巧来实现这一目标。如果您将CSV输入转换为如下列表:

$in = array_map("str_getcsv", explode("\n", $table));

然后你就可以遍历它:

$data = array();

foreach ($in as $row) {
    list ($depth, $key, $value) = $row;

    $r = & $data;  // start from base array, then submerge $n last keys
    while ($depth--) { end($r); $r = & $r[key($r)]; }

    $r[$key] = $value;
}

至少适用于您的示例:

Array
(
    [id] => 12
    [name] => Name
    [pages] => Array
        (
            [0] => Page 1
            [1] => Page 2
            [2] => Page 3
        )

    [items] => Array
        (
            [0] => Array
                (
                    [id] => 4
                    [title] => Example Items
                )

        )

)