使用php从mysql数据库构建多维数组

时间:2014-03-03 02:04:07

标签: php mysql multidimensional-array

我有一个理论上的问题,我似乎无法弄明白。想象一下,我在数据库中有以下数据:

Main    Sub1   Sub2
a       x      y
x       t      u
u       f      g

我想在PHP / mYSQL中创建一个多维数组,主要是询问“每个'主要'组件是由什么构成的?”

结果将是这样的:

Array
   (
   [0] => a
     (
     [0] => x
       (
       [0] => t
       [1] => u
       )
         (
         [0] => f
         [1] => g
         )
     [1] => y
     )
   )

我的努力导致了许多数组,而不是多维数组。

1 个答案:

答案 0 :(得分:1)

你可以使用引用来解决这个问题,虽然结果会有点混乱:

$res = [];

foreach ($rows as $row) {
    // check if we have each sub component
    if (!isset($res[$row['sub1']])) {
        $res[$row['sub1']] = $row['sub1'];
    }
    if (!isset($res[$row['sub2']])) {
        $res[$row['sub2']] = $row['sub2'];
    }
    // build new component with references to the sub components
    $res[$row['main']] = [&$res[$row['sub1']], &$res[$row['sub2']]];
}

print_r($res);

输出

Array
(
    [x] => Array
        (
            [0] => t
            [1] => Array
                (
                    [0] => f
                    [1] => g
                )

        )

    [y] => y
    [a] => Array
        (
            [0] => Array
                (
                    [0] => t
                    [1] => Array
                        (
                            [0] => f
                            [1] => g
                        )

                )

            [1] => y
        )

    [t] => t
    [u] => Array
        (
            [0] => f
            [1] => g
        )

    [f] => f
    [g] => g
)

您可以通过仅过滤掉数组来清理结果:

print_r(array_filter($res, 'is_array'));

输出

Array
(
    [x] => Array
        (
            [0] => t
            [1] => Array
                (
                    [0] => f
                    [1] => g
                )

        )

    [a] => Array
        (
            [0] => Array
                (
                    [0] => t
                    [1] => Array
                        (
                            [0] => f
                            [1] => g
                        )

                )

            [1] => y
        )

    [u] => Array
        (
            [0] => f
            [1] => g
        )

)