foreach在插入数组时重复该值

时间:2014-07-19 04:20:46

标签: php arrays wordpress foreach

让我看到我在阵列中有多个帖子。我希望从数组中获取所有值并插入到数据库中。

当我Print_r($posts); its给出所有std obj数组时,我认为循环中存在问题,因为当我用回声做foreach时,每件事情都会变得完美。

    $posts = $topic->curatedPosts; 
    $x = count($posts); // output 20 post this is perfect

    foreach($posts as $post){
    // if i add echo $ title & $content its works its shows me different post.  
        $title = $post->title;
        $content = $post->htmlContent;

        // Create post object
/* but when i try to add in array and save all post in database so everytime only one post return many times. */
        $my_post = array(
            'post_title'    => $title,
            'post_content'  => $content,
            'post_status'   => 'publish',
            'post_author'   => 1,
            'tax_input'     => array('category'),
            'post_category' => array(744)
        );

        // Insert the post into the database
        wp_insert_post($my_post); 
    }

我也试过这个但结果相同 Post added same `

$x = count($posts);
$y = 0;

while($y <= $x){

 foreach($posts as $post){
  $title = $post->title;
  $content = $post->htmlContent;

  // Create post object
$my_post = array(
  'post_title'    => $title,
  'post_content'  => $content,
  'post_status'   => 'publish',
  'post_author'   => 1,
  'tax_input' => array('category'),
  'post_category' => array(744)
);

// Insert the post into the database
wp_insert_post($my_post);

}
$y++;
}

`

Print_r($posts)

请帮助我guyes我真的需要你的帮助时间不多了

它不会在插件上工作,但是当我在自定义模板中添加所有代码时,它的作品......任何专家都知道我做错了什么。

0 个答案:

没有答案