简体   繁体   中英

Build multidimensional array from mysql database using php

I have a theoretical question that I cannot seem to figure out. Imagine I have the following data in a database:

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

I want to make a multidimensional array in PHP/mYSQL by essentially asking "what is each 'main' component made of?"

The result would be something like this:

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

My efforts result in lots of arrays, instead of a multidimensional array.

You can use references to solve this, although the results will get a bit messy:

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

Output

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
)

You can clean up the results by filtering out only the arrays:

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

Output

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
        )

)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM