【问题标题】:Remove an array from an array inside foreach从 foreach 中的数组中删除一个数组
【发布时间】:2021-09-10 08:04:18
【问题描述】:

我找到了有关从 foreach 中的数组中删除单个元素的建议,但在尝试从数组中删除数组时无法使其正常工作。这是我正在使用的:

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

}
?>

【问题讨论】:

    标签: php arrays wordpress foreach


    【解决方案1】:

    我建议使用 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',
        ]);
    }
    ?>
    

    【讨论】:

    • 感谢您的回复 - 但是我需要在第二个 foreach 循环中从 $all_posts 数组中删除 $same_title_posts 数组的内容。
    【解决方案2】:

    找到的解决方案 - 在我添加的函数的开头:

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

    然后在第一个 foreach 的开头我添加了:

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

    在我添加的第二个 foreach 末尾:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-27
      • 2021-07-27
      • 2019-06-19
      • 2013-02-19
      • 1970-01-01
      • 1970-01-01
      • 2016-04-03
      • 1970-01-01
      相关资源
      最近更新 更多