Search code examples
phpmysqlarraysjvectormap

Fetch Data From Database and Match with The static Array


I am Working with the Jvector Map, In that I want to find the Country Code based on the Countries That I have in database as String.

For eg. IF the Country in Database is 'Australia' it should automatically convert it into its Country Code 'AU'

Suppose I recieved Multiple Country Names it should Automatically convert all the names to Country Codes at Once.

I Have an Associated Array of the Country Names With Country Codes , For eg.

    $keyvalue = 

  array("Bangladesh"=>"BD",
        "Belgium"=>"BE", 
        "Burkina Faso"=>"BF",
        "Bulgaria"=>"BG",
        "Bosnia and Herz"=>"BA", 
        "Brunei"=>"BN",
        "Bolivia"=>"BO",
        "Japan"=>"JP", 
        "Burundi"=>"BI", );

As I have all the country Codes stored in static array. How Can I match them with the Country Names I fetched From The Database.

I Have Tried the following php Code :

<?php
  $query = "SELECT user_country FROM users" ;
  $result = mysqli_query($conn,$query) ;

  foreach($keyvalue as $x => $x_value) {
 "Key=" . $x . ", Value=" . $x_value;
 "<br>";
}

foreach($result as $rec => $x_value)
{
echo  $rec['user_country'] ."  : "  . $rec[$x_value];
}   
?>

I Hope My Question is Clear. What Am I Missing and How Can I persue this particular problem. Pardon my code, it may have multiple flaws in it


Solution

  • I suppose you just want to echo them judging from your second loop, in that case you can use

      $keyvalue = //your array here;
      $query = "SELECT user_country FROM users" ;
      $result = mysqli_query($conn,$query) ;
      echo "<table>";
      echo "<tr><th>Country</th><th>Country Code</th></tr>";
      while($row = mysqli_fetch_assoc($result)){
        echo "<tr> ";
            echo "<td>" . $row['user_country'] . "</td>";
            echo "<td>" . $keyvalue[$row['user_country']] . "</td>";
      }
      echo "</table>";