【问题标题】:check if array values contain another array's values and get the relevant key检查数组值是否包含另一个数组的值并获取相关键
【发布时间】:2025-12-31 20:00:02
【问题描述】:

我有一系列这样的国家/地区名称:

$countryList = array(
"AF" => "Afghanistan",
"AL" => "Albania",
"DZ" => "Algeria",
# [...]
);

另一个数组 $uniList 包含具有大学附属关系的字符串,例如:

$uniList = array(
14 => array("id" => 14, "uni" => "University of Kabul, Afghanistan"),
20 => array("id" => 21, "uni" => "University Tirana, Albania, Department of Chemistry"),
23 => array("id" => 23, "uni" => "Oxford, U.K."),
# [...]
);

我想遍历所有$uniList-values 并查看$countryList 中的任何国家名称是否出现在那里。

如果找到一个国家/地区,我想将国家/地区代码(来自$countryList 的数组键,例如AF 用于Afghanistan)插入到 MySQL 行中。

类似这样的:

foreach($uniList as $row) {

   if($row['uni'] contains any of $countryList) { # perhaps strpos()?

        $stmt = $conn->prepare("UPDATE `table` SET column = :countrycode WHERE id = :id");
        $stmt->bindValue(":countrycode", $countryList[key]);
        $stmt->bindValue(":id", $row['id']);
        $stmt->execute();

   }

}

如何实现?

最终,我的目标是拥有一个类似于以下内容的 MySQL 表:

| id | uni                                                 | country     |
| -- | --------------------------------------------------- | ----------- |
| 14 | University of Kabul, Afghanistan                    | Afghanistan |
| 20 | University Tirana, Albania, Department of Chemistry | Albania     |
| 23 | Oxford, U.K.                                        | U.K.        |
| 45 | University of Vienna                                | NULL        |

【问题讨论】:

  • 为什么会有“INSERT...WHERE...”?
  • @ManuelGuzman,哦,我更正为UPDATE ... SET ...。谢谢指出!

标签: php mysql arrays


【解决方案1】:

似乎您只需要一个嵌套循环和strpos()

类似的东西

foreach($countryList as $abr => $country) {
    foreach($uniList as $uni) {
        if(strpos($uni['uni'], $country) !== false) {
            
            //insert
            $stmt = $conn->prepare("UPDATE `table` SET column = :countrycode WHERE id = :id");
            $stmt->execute([
                'countrycode' => $country,
                'id' => $uni['id']
            ]);
            
        }
    }
}

如果您希望文本不区分大小写,请使用stripos()

【讨论】:

  • 完美,有效,谢谢! (抱歉——当然应该是UPDATE ... SET ...,而不是INSERT ...