I use facebook graph api to retrieve my facebook posts and display them on my website.

So far I have filtered my post by tags using this code (this code retrieves the FB posts tagged with -fr- / others post are tagged with -en- : which allow me to sort my post by languages)

      $string = $post['message'];
      $array = array("-fr-");
      if(0 < count(array_intersect(array_map('strtolower', explode(' ', $string)), $array)))

First question: I am trying now to retrieve my post based on my language tags PLUS on one another tags.

I have tied:

$array = array("-fr-", "#science");

But all the posts containing EITHER -fr- OR #science are display. What I want is to display all the post containing the tags -fr- AND #science.

Second question: I would also need to retrieve posts with optional tags. For example I have those posts with these tags:

Post 1= -fr- #science #education
Post 2= -fr- #science #politics
Post 3= -fr- #science #animals

I would like to retrieve only post 1 and 2.

So -fr- and #science would be mandatory but #education and #politics would be a "EITHER... OR..." request (this request would be like: array("#education", "#politics"); )

Any idea how to do it? Thanks a lot for your help!

有帮助吗?

解决方案

I'd extract that algorithm in a function:

$string = $post['message'];
$data = array_map('strtolower', explode(' ', $string));

$tag = '-fr-';

function filterByTag($data, $tags) {
    return array_intersect($data, $tags);
}

$filteredData = filterByTag($data, array('-fr'));
// AND
$filteredData = filterByTag($filteredData, array('#science'));

Calling it successively results in an AND condition. Calling it with multiple array values in the $tags parameter would be an OR.

其他提示

Try this solution (works in PHP 5.3+):

function filterMessages($a_messages, $a_mandatory, $a_options) {
    return array_filter($a_messages, function ($text) use ($a_mandatory, $a_options) {
        $text = " $text ";
        $fn = function ($v) use ($text) {
            return stripos($text, " $v ") !== false;
        };
        return
            count(array_filter($a_mandatory, $fn)) == count($a_mandatory) &&
            count(array_filter($a_options, $fn)) > 0;
    });
}

$a_messages = array(
'-fr- #science #education',
'-fr- #science #politics',
'-fr- #science #animals',
);
$a_mandatory = array('-fr-', '#science');
$a_options = array('#education', '#politics');
print_r(filterMessages($a_messages, $a_mandatory, $a_options));
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top