循环遍历数组/对象数组

时间:2011-10-22 22:44:29

标签: php arrays wordpress object loops

我有类似于以下结构:

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
            )

    )
)

我在这里尝试做的是迭代这些结果,以便我可以使用它们来形成查询。

假设wp_postmeta表中的所有数据都从数据库中删除,并且该数组在删除之前包含该表的数据。我想在数组中保存这些已保存的数据,并使用这些旧值重置表。

I.e循环遍历数组并将其插入为sql:INSERT INTO wp_postmeta(meta_id,post_id,meta_key,meta_value)VALUES(1,2,'_ wp_page_template','default')

1 个答案:

答案 0 :(得分:1)

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
  }
}

您可以iterate over object properties就像使用数组一样,而stdClass中的所有内容都是公开的,因此上述内容应该没有问题。