我有一個多為陣列如下,如何將下列資料用子母關係存入資料庫,並轉化為id,name,paren欄位存入。
Ex
table:
id, name, parent, depth
1 , a , 0 , 1
2 , b , 1 , 2
3 , c , 1 , 2
4 , d , 1 , 2
5 , e , 0 , 1
6 , f , 5 , 2
7 , g , 6 , 3
8 , h , 6 , 3
$ary = [
    "a" => [
        "b",
        "c",
        "d",
    ],
    "e" => [
        "f" => [
            "g",
            "h",
            "i",
        ],
        "j" => [
            "k",
            "l",
            "m",
        ],
        "n" => [
            "o",
            "p",
            "q",
        ],
    ],
    "r" => [
        "s" => [
            "t",
            "u",
            "v",
            "w",
            "x",
            "y",
        ],
        "z" => [
            "aa",
            "bb",
            "cc",
            "dd",
            "ee",
            "ff",
        ],
        "gg" => [
            "hh",
            "ii",
            "jj",
            "kk",
            "ll",
            "mm",
        ],
    ],
    "nn" => [
        "oo",
        "pp",
        "qq",
        "rr",
        "ss",
        "tt",
    ],
    "uu" => [
        "vv",
        "ww",
        "xx",
        "yy",
        "zz",
    ],
];
$result = [];
$iteratorStack = [(new ArrayObject($ary))->getIterator()];
$parentIdStack = [0];
$idx = 0;
$idCount = 1;
while ($idx >= 0) {
    $it = $iteratorStack[$idx];
    $parentId = $parentIdStack[$idx];
    if (!$it->valid()) {
        unset($iteratorStack[$idx]);
        unset($parentIdStack[$idx]);
        --$idx;
        continue;
    }
    $key = $it->key();
    $val = $it->current();
    if (gettype($key) === 'integer') {
        $key = $val;
        $val = false;
    }
    $myId =  $idCount++;
    $result[] = [
        'id' => $myId,
        'name' => $key,
        'parent' => $parentId,
        'depth' => $idx + 1
    ];
    if (gettype($val) === 'array') {
        ++$idx;
        $iteratorStack[$idx] = (new ArrayObject($val))->getIterator();
        $parentIdStack[$idx] = $myId;
    }
    $it->next();
}
foreach ($result as $row) {
    printf("%s, %s, %s, %s\n", $row['id'], $row['name'], $row['parent'], $row['depth']);
}
多數資料庫(MS SQL、PostgreSQL...)均支援JSON,直接存入整個資料結構,也可以使用NoSQL資料庫,好處是不需拆成多個資料表,要查詢時又要join多個資料表。
可參閱: