【问题标题】:PHP: retrieve multiples arrays using AND not ORPHP:使用 AND 而不是 OR 检索多个数组
【发布时间】:2014-02-10 08:50:05
【问题描述】:

我使用 facebook graph api 来检索我的 facebook 帖子并将它们显示在我的网站上。

到目前为止,我已经使用此代码按标签过滤了我的帖子(此代码检索带有 -fr- 标记的 FB 帖子/其他帖子带有 -en- 标记:这允许我按语言对我的帖子进行排序)

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

第一个问题: 我现在正在尝试根据我的语言标签加上另一个标签来检索我的帖子。

我已经绑定了:

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

但所有包含 -fr-#science 的帖子都会显示。我想要的是显示所有包含标签-fr-#science 的帖子。

第二个问题: 我还需要检索带有可选标签的帖子。例如,我有这些带有这些标签的帖子:

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

我只想检索帖子 1 和 2。

所以-fr-#science 是强制性的,但#education#politics 将是“EITHER... OR...”请求(此请求类似于:array("#education", "#politics"); )

知道怎么做吗?非常感谢你的帮助!

【问题讨论】:

  • 第一个问题:为什么不对每个标签依次运行相同的算法,在每一步过滤结果数组?
  • 非常感谢你是个天才 Sergiu!我刚刚在第一个算法的下方添加了一个$array1 = array("#science"); if(0 &lt; count(array_intersect(array_map('strtolower', explode(' ', $string)), $array1))) 并且......它正在工作!非常感谢!
  • @SergiuParaschiv 顺便说一句,你的把戏也回答了我的第二个问题:$array3 = array("#education", "#politics");!请发布它作为答案,我非常感谢你!

标签: php arrays explode array-intersect


【解决方案1】:

我会在一个函数中提取该算法:

$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'));

连续调用它会导致AND 条件。 在$tags 参数中使用多个数组值调用它会是OR

【讨论】:

    【解决方案2】:

    试试这个解决方案(适用于 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));
    

    【讨论】:

    • 非常感谢! if(0 &lt; count(array_intersect(array_map('strtolower', explode(' ', $string)), $array))) 不能与 5.3 以上的 PHP 一起使用吗?(我使用的是 5.3.16,它仍在工作)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-01
    • 2015-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多