• Resolved branch

    (@branch)


    Is there any way to get the intersect of two WP_Query result arrays? array_intersect obviously isn’t going to do it on an object array like this. Trying to compare the values and unset any that didn’t match erased my whole array, probably because I don’t know how to specify a meaningful value, like title or id, or the right key.

    I’m working on an advanced search function for a site, and want to get posts that are in any of two sub-sets of categories. So: get posts that are in any of the categories (1 or 2 or 3) and are also in any of the categories (x or y or z). What I do not want is: posts in any of the categories (1 or 2 or 3 or x or y or z). I want the overlap of the two sets.

    None the built-in ways to query for posts, like get_posts or query_posts, seem to be able to do this. I can’t use category__in twice in the same query, alas. The only solution short of writing an SQL query (which I suck at) that I’ve thought of so far is to run two queries, one on each subset of categories, and then compare them for the intersection between the two. Does anyone know of a way to do this on such a complicated object array? Or know of another option to reach the same end?

    The two queries I currently have are as follows. Individually, they work exactly as I want them to.

    $query1 = new WP_Query(array('category__in'=>$j_post_cats, 'tag__in'=>$j_post_tags));
    
    $query2 = new WP_Query(array('category__in'=>$j_post_catsg, 'tag__in'=>$j_post_tags));

    My first pass at a comparison and unset looks like this:

    foreach ($query1 as $key=>$value){
    	if (!in_array($value,$query2)){
    		unset($query1[$key]);
    	}
    }

    I know, in a general way, why it isn’t working. I just don’t know how to fix it! Any thoughts?

Viewing 1 replies (of 1 total)
  • Thread Starter branch

    (@branch)

    Ha! I think I got it. The foreach I needed is:

    foreach ($query1->posts as $key=>$value){
    	if (!in_array($value,$query2->posts)){
    		unset($query1->posts[$key]);
    	}
    }

    Object syntax for the win.

    I still need to figure out where the bizarre entries with nothing but a single “word” in them are coming from. I suspect this is another case like the “empty” category descriptions that actually contain a break tag. But the comparison is working, at least.

Viewing 1 replies (of 1 total)
  • The topic ‘Way to compare two WP_Query arrays for intersect?’ is closed to new replies.