skip to Main Content

I have found advice on removing single elements from an array within foreach, but wasn’t able to get it working when trying to remove an array from an array. Here’s what I’m working with:

<?php
$all_posts = array('1', '2', '3', '4', '5'); // example array of WordPress post IDs from a get_posts function

foreach ($all_posts as $op_post) {

    $op_title = get_the_title($op_post);
    $same_title_posts = get_posts([ // get posts with same title
        'title' => $op_title,
        'post__not_in' => array($op_post),
        'posts_per_page' => -1,
        'fields' => 'ids',
    ]);

    // example contents of $same_title_posts - array('1', '2')

    foreach($same_title_posts as $same_title_post) {
        // function
    }

     // before $all_posts loops again, need to remove contents of $same_title_posts array from $all_posts array

}
?>

2

Answers


  1. Chosen as BEST ANSWER

    Solution found - at the beginning of the function I added:

    $skip_array = array(); // start with an empty array to avoid errors
    

    Then at the beginning of the first foreach I added:

    if(!in_array($id, $skip_array)) { // check if foreach ID has been added to skip_array
      // function
    }
    

    At the end of the second foreach I added:

    $skip_array[] = $id; // add ID that has been processed to skip_array
    

  2. i suggest by using array_diff

    <?php
    $all_posts = array('1', '2', '3', '4', '5'); // example array of WordPress post IDs from a get_posts function
    $same_title_posts = array('1', '2'); //
    $arrays = array_diff($all_posts, $same_title_posts);
    
    //then loop $arrays
    
    foreach ($arrays as $op_post){
        $op_title = get_the_title($op_post);
        $same_title_posts = get_posts([ // get posts with same title
            'title' => $op_title,
            'post__not_in' => array($op_post),
            'posts_per_page' => -1,
            'fields' => 'ids',
        ]);
    }
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search