0

I have an array of country names like this:

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

Another array, $uniList, contains strings with university affiliations, e.g.:

$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."),
# [...]
);

I want to loop through all $uniList-values and see whether any of the country names in $countryList appear there.

If a country is found, I would like to insert the country code (the array key from $countryList, e.g. AF for Afghanistan) into a MySQL row.

Something like this:

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();

   }

}

How is it possible to achieve it?

My goal, in the end, is to have a MySQL table that should look similar to this:

| 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        |
2
  • Why you have "INSERT... WHERE..."? Commented Jan 24, 2022 at 17:24
  • @ManuelGuzman, oh, I corrected it to UPDATE ... SET .... Thanks for pointing out! Commented Jan 24, 2022 at 17:35

1 Answer 1

1

Seems like you just need a nested loop and strpos().

Something like this

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']
            ]);
            
        }
    }
}

If you want the text to match regardless of case, use stripos()

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, it works, thank you! (And sorry -- it should have been UPDATE ... SET ..., of course, and not INSERT ...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.