【问题标题】:Delete multiple values from multidimensional array从多维数组中删除多个值
【发布时间】:2014-11-17 14:54:02
【问题描述】:

我有一个来自 WordPress 的 get_posts() 函数的数组。

$posts:

array(15) {
[0]=>
  object(WP_Post)#285 (24) {
    ["ID"]=>
    int(253)
    ["post_author"]=>
    string(1) "1"
    ["post_date"]=>
    string(19) "2014-04-17 18:36:27"
    ["post_date_gmt"]=>
    string(19) "2014-04-17 18:36:27"
    ["post_content"]=>
    string(8) "gsdljdkf"
    ["post_title"]=>
    string(10) "Shortcoded"
    ["post_excerpt"]=>
    string(0) ""
    ["post_status"]=>
    string(7) "publish"
    ["comment_status"]=>
    string(6) "closed"
    ["ping_status"]=>
    string(4) "open"
    ["post_password"]=>
    string(0) ""
    ["post_name"]=>
    string(12) "shortcoded-2"
    ["to_ping"]=>
    string(0) ""
    ["pinged"]=>
    string(0) ""
    ["post_modified"]=>
    string(19) "2014-04-17 18:36:27"
    ["post_modified_gmt"]=>
    string(19) "2014-04-17 18:36:27"
    ["post_content_filtered"]=>
    string(0) ""
    ["post_parent"]=>
    int(0)
    ["guid"]=>
    string(51) "http://XXX.0.0.1:4001/wordpress/board/shortcoded-2/"
    ["menu_order"]=>
    int(0)
    ["post_type"]=>
    string(10) "board_post"
    ["post_mime_type"]=>
    string(0) ""
    ["comment_count"]=>
    string(1) "0"
    ["filter"]=>
    string(3) "raw"
  }
  [1]=>
  object(WP_Post)#284 (24) {
    (so on and so forth for all posts)
}

我有一个数组,其中包含要排除的帖子 ID。

$ids_of_posts_to_exclude:

array(3) {
  [0]=> string(253)
  [1]=> string(456)
  [2]=> string(789)
}

如何从$posts中删除id在$ids_of_posts_to_exclude中的帖子?

【问题讨论】:

标签: php arrays multidimensional-array


【解决方案1】:

您可以使用 foreach 循环和 in_array() 函数来执行此操作。像这样:

foreach($posts as $key => $post) {
    // if post id is inside the ids of posts to be excluded
    if(in_array($post->ID, $ids_of_posts_to_exclude)) {
        unset($posts[$key]); // remove that key
    }
}

【讨论】:

  • @simplethings 很高兴它有帮助
【解决方案2】:

使用array_filter的另一种方式

$filtered_posts = array_filter($posts,function($post) use ($ids_of_posts_to_exclude) {
    return in_array($post->ID,$ids_of_posts_to_exclude);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-25
    • 2017-06-23
    • 1970-01-01
    • 1970-01-01
    • 2014-02-13
    • 2011-04-05
    • 2013-11-05
    相关资源
    最近更新 更多