【发布时间】: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 ...。谢谢指出!