【问题标题】:Looping through array of array/objects循环遍历数组/对象数组
【发布时间】:2011-10-22 22:44:28
【问题描述】:

我有类似以下结构的东西:

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 表中的所有数据都从数据库中删除,并且该数组包含该表在删除之前的数据。我想把这个保存在数组中的数据用这些旧值重置表。

即循环遍历数组并将其作为 sql 插入:INSERT INTO wp_postmeta (meta_id, post_id, meta_key, meta_value) VALUES (1, 2, '_wp_page_template', 'default')

【问题讨论】:

  • 问题出在哪里?
  • 问题是我不知道如何迭代这些结果来形成查询。
  • 查看 WP API 如何将对象作为注释插入。然后你只需要遍历数组并触发每个值的插入。
  • 一个对象作为评论?我能找到的唯一函数是 $wpdb->insert( $wpdb->table_name, array( 'field_one' => $newvalueone, 'field_two' => $newvaluetwo ) );

标签: php arrays wordpress object loops


【解决方案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 中,所有内容都是公开的,因此上述操作应该没有问题。

【讨论】:

  • 戴夫,非常感谢 - 我会尽快尝试一下。但是有一个问题 - 假设我们以此作为字段 => 值的示例:[comment_content] => 这是派对时间''''sss。这无疑会破坏您的查询 - 纠正这个问题的简单方法?
  • 哦,刚刚看到你在 $val 旁边的评论。对。 :p
猜你喜欢
  • 2016-09-07
  • 1970-01-01
  • 2016-07-28
  • 2017-01-29
  • 2015-10-15
  • 2015-12-28
  • 1970-01-01
相关资源
最近更新 更多