【问题标题】:PHP - Search one associative array with an array of values, then create a new array with matching resultsPHP - 使用一组值搜索一个关联数组,然后创建一个具有匹配结果的新数组
【发布时间】:2012-07-05 22:29:35
【问题描述】:

我有一个关联数组如下:

{
  "organizations":[
    {
      "name":"10sheet",
      "owner_name":"Me"
    },
    {
      "name":"12Gigs",
      "owner_name":"Me"
    },
      "name":"24\/7 Card",
      "owner_name":"Me as well"
    },
}

我想使用第一个数组中的名称字段与以下关联数组中的名称字段进行搜索:

[{"name": "Wetpaint",
  "permalink": "wetpaint",
  "category_code": "web"},
 {"name": "AdventNet",
  "permalink": "adventnet",
  "category_code": "enterprise"},
 {"name": "Zoho",
  "permalink": "zoho",
  "category_code": "software"},
 {"name": "Digg",
  "permalink": "digg",
  "category_code": "web"},
 {"name": "24/7 Card",
  "permalink": "247-card",
  "category_code": "other"}]

如果有匹配项,则将永久链接字段中的值放入一个新数组中。此外,在第一个数组中存在转义问题,例如 24/7 而不是 24/7,并且搜索不应区分大小写。我正在尝试用 PHP 编写此代码,而使用这两个 API 让我感到很痛苦。

感谢您的帮助!

-格雷格

【问题讨论】:

    标签: php arrays search associative


    【解决方案1】:

    未经测试,但应该可以工作:

    <?php
    $result = array();
    foreach($obj["organizations"] as $o) {
        foreach($obj2 as $o2) {
            if(stristr($o["name"], $o2["name"])) {
                $result[] = $o2["permalink"];
            }
        }
    }
    ?>
    

    $obj 是你的第一个数组,$obj2 第二个.. $result 包含匹配项。

    【讨论】:

    • 感谢您的回复。我几乎可以使用它,但我想做一个 array_search,所以如果我在一个数组名称中有“Reddit”,而另一个数组名称中有“reddit”,它会找到匹配项。但是,如果我有例如“redditmania”,它不会返回匹配项。
    • preg_match 而不是 stristr。使用通配符传递正则表达式。再次反转以使其双向工作。 php.net/manual/en/function.preg-match.php
    猜你喜欢
    • 2011-02-22
    • 1970-01-01
    • 1970-01-01
    • 2020-01-27
    • 2012-10-22
    • 2022-01-12
    • 1970-01-01
    • 2015-08-28
    • 2013-08-22
    相关资源
    最近更新 更多