Question

i have country list csv with its code i use below code to read the csv

function readCSV($csvFile){
    $file_handle = fopen($csvFile, 'r');
    while (!feof($file_handle) ) {
        $line_of_text[] = fgetcsv($file_handle, 1024);
    }
    fclose($file_handle);
    return $line_of_text;
}

and i got result like

Array
(
    [0] => AD
    [1] => Andorra
    [2] => Andorre
)
Array
(
    [0] => AE
    [1] => United Arab Emirates
    [2] => Émirats arabes unis
)
Array
(
    [0] => AF
    [1] => Afghanistan
    [2] => Afghanistan
)
Array
(
    [0] => AG
    [1] => Antigua and Barbuda
    [2] => Antigua-et-Barbuda
)
Array
(
    [0] => AI
    [1] => Anguilla
    [2] => Anguilla
)

i want to build some relation ship like if write "Anguilla" in text box i get its cod "AI" and so on for each but could not figure out how to make relationship between them for key 0 and key 1

Was it helpful?

Solution

You can achieve this using associative arrays.

Replace

$line_of_text[] = fgetcsv($file_handle, 1024);

With

$line = fgetcsv($file_handle, 1024);
$line_of_text[$line[1]] = $line;

This way your function will return something like:

Array
(
    [Andorra] => Array
        (
            [0] => AD
            [1] => Andorra
            [2] => Andorre
        )

    [United Arab Emirates] => Array
        (
            [0] => AE
            [1] => United Arab Emirates
            [2] => Émirats arabes unis
        )

    ....
)

So you will be able to get the row for Anguilla using $line_of_text['Anguilla'].

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top