2014-09-23 140 views
1

我有一個WordPress'get_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) 
} 

如何刪除其ID在$ids_of_posts_to_exclude$posts列出的職位?

(一些細節,一些細節,一些細節)

+0

看看'''array_dif'''另一種方式 - http://php.net/manual/en/function.array-diff。 php – Kolors 2014-09-23 12:02:53

+0

循環然後取消設置 – Ghost 2014-09-23 12:25:15

回答

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 
    } 
} 
+0

@simplethings很高興幫助 – Ghost 2014-09-23 12:56:02

1

使用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); 
});