0

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

1 Answer 1

1

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'].

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

Comments

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.