0
votes

I have something similar to the following structure:

Array
(
    [wp_postmeta] => Array
    (
        [0] => stdClass Object
            (
                [meta_id] => 1
                [post_id] => 2
                [meta_key] => _wp_page_template
                [meta_value] => default
            )

    )

    [wp_comments] => Array
    (
        [0] => stdClass Object
            (
                [comment_ID] => 1
                [comment_post_ID] => 1
                [comment_author] => Mr WordPress
                [comment_author_email] => 
                [comment_author_url] => http://wordpress.org/
                [comment_author_IP] => 
                [comment_date] => 2011-10-20 03:06:23
                [comment_date_gmt] => 2011-10-20 03:06:23
                [comment_content] => Hi, this is a comment.
                [comment_karma] => 0
                [comment_approved] => 1
                [comment_agent] => 
                [comment_type] => 
                [comment_parent] => 0
                [user_id] => 0
            )

    )
)

What I'm trying to do here is iterate over these results so I can use them to form a query.

Assume all the data within the wp_postmeta table is deleted from the database and this array contains the data of that table before it was deleted. I want to take this saved data in the array and reset the table with these old values.

I.e Looping through the array and inserting this as sql: INSERT INTO wp_postmeta (meta_id, post_id, meta_key, meta_value) VALUES (1, 2, '_wp_page_template', 'default')

1
And what is the problem?deviousdodo
Problem is I can't figure out how to iterate over these results to form the query.mousesports
Look into the WP API how to insert an object as a comment. Then you only need to foreach over the array and fire the insert per value.hakre
An object as a comment? Only function I can find is $wpdb->insert( $wpdb->table_name, array( 'field_one' => $newvalueone, 'field_two' => $newvaluetwo ) );mousesports

1 Answers

1
votes
foreach ($outerArray as $tableName => $tableData) { // Loop outer array
  foreach ($tableData as $row) { // Loop table rows
    $cols = $vals = array();
    foreach ($row as $col => $val) { // Loop this row
      $cols[] = $col;
      $vals[] = $val; // You may need to escape this before using it in a query...
    }
    // Build the query
    $query = "INSERT INTO $tableName (".implode(', ',$cols).") VALUES ('".implode("', '",$vals)."')";
    // Do the query here
  }
}

You can iterate over object properties just like you can with an array, and in a stdClass everything is public, so the above should work no problem.