简体   繁体   中英

How save data to database using recursion

My mysql table looks like this:

page_id     parnt_id    page_name
------------------------------------
1           0           AboutUs
2           1           Contact_us
3           2           Home
4           2           Currear

and I have an array that looks like this:

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

                                )
                        )
                )
        )
)

How can I add this above array into a database using recursion?

$all_pages = $given_array;

function save_page($page, $parent_id = 0) {

  $page_id = $page['id'];
  $sql = "INSERT INTO table_name (page_id, parent_id)
         VALUES ($page_id, $parent_id)";
  mysql_query($sql);

  if(array_key_exists('children', $page)) {
    save_page($page['children'], $page['id']);
  }
}

save_page($all_pages);

Instead of doing the recursion yourself, you can use some helper classes; assuming the following data:

$data = [[
        'id' => 1,
        'name' => 'About_Us',
        'children' => [[
                'id' => 2,
                'name' => 'Contact_Us',
                'children' => [[
                        'id' => 3,
                        'name' => 'Home',
                ], [
                        'id' => 4,
                        'name' => 'Careers',
                ]],
        ]],
]];

You can use RecursiveArrayIterator to perform the iteration for you so that you can perform your database work in a simple loop:

$stmt = $db->prepare('INSERT INTO pages (page_id, parent_id, page_name) 
    VALUES (?, ?, ?)');

$it = new RecursiveIteratorIterator(
    new RecursiveArrayIterator($data), 
    RecursiveIteratorIterator::CHILD_FIRST
);

foreach ($it as $key => $node) {
    if (!isset($node['id'])) {
        continue; // skip nodes without an id field
    }

    if ($it->getDepth() > 1) {
        // go two levels down for the parent
        $parent = $it->getSubIterator($it->getDepth() - 2)->current();
    } else {
        $parent = null;
    }

    $stmt->execute([$node['id'], $parent ? $parent['id'] : 0, $node['name']]);
}

Something like below:

function importPages($pages, $parent_id = 0) {
  foreach ($pages as $page) {
    insertToDB($page['id'], $parent_id);
    foreach ($page['children'] as $child) {
      importPages($child, $page['id']);
    }
  }
}
function recurInsert($node, $parent) {
    $que = "INSERT INTO `table_name` (page_id, parnt_id) VALUES ('".$node['id']."', '".$parent."')";
    // process this query, you can add page name also, 
    // but I don't know where you store it
    if (is_array($node['children'])) {
        foreach ($children as $child) {
            recurInsert($child, $node['id']);
        }
    }
}
// start recursion 
recurInsert($your_array, 0);

oh, I just noticed @xdazz and guy from India already answered nearly the same

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