Skip to content
Advertisement

How to dynamically get column value from csv file using php

i have two columns in csv file Name and Phone . If i given phone number as a variable $searchStr = "6059574150"; it has to find number in csv file and i need that contact name to get access dynamicaly like this $data[‘Name’] instead of $data[‘0’] MY php code

$header = array();
$final_result = array();
$file = fopen('example.csv', 'r');
if($file){
$row = 1;
while ($data = fgetcsv($file, 10000, ",")){

    if($row == 1){
        $header = array_values($data);
    }
    else{
        $final_result[] = array_combine($header, array_values($data));
    }

$row++;
}

}
    echo "<pre>";
    print_r($final_result);

my output is like this

Array
 (
[0] => Array
    (
        [Names] => MICHAEL
        [Phone] => 6059342614
    )

[1] => Array
    (
        [Names] => GLENN
        [Phone] => 6056296061
    )


 )

how to directly access column ? like this $data[‘Name’]

Advertisement

Answer

If phone numbers are unique, you could do something like this:

<?php

$final_result = array();
$file = fopen('example.csv', 'r');

if($file) {
    $header = fgetcsv($file, 10000, ",");

    while ($data = fgetcsv($file, 10000, ",")) {
        $final_result[$data[1]] = $data[0];
    }

}
?>

If you have more than one name (person) for each phone number, you can concatenate them $final_result[$data[1]] .= ',' . $data[0];.

Example result:

array (
  phone1 => 'name1',
  phone2 => 'name2',
  phone3 => 'name3',
)

To search a name from a phone number you have to do: $final_result[phone_number] and you get the name.


In your output array “$final_result” you can look for a Name by phone number this way:

$foundKey = array_search('pone_number_to_search', array_column($final_result, "Phone"));

$foundNames = $final_result[$foundKey]["Names"];
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement