0

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

  • I don't understand the question. Do you not know how array access works? Are you asking how you can achieve a different structure? – El_Vanja Apr 09 '21 at 15:30
  • And as a side note for the future: please share dumps of data by using `var_export` instead of `print_r`. That way we'll be able to directly copy your entire array in case we need it for testing. – El_Vanja Apr 09 '21 at 15:31
  • @El_Vanja thanks for replay my question if given phone number $searchStr = "6059574150"; is matched in csv file how to get that contact name dynamically – Bala Chandar Apr 09 '21 at 15:39
  • In that case, have a look [here](https://stackoverflow.com/questions/31906271/using-php-to-search-csv-by-column). – El_Vanja Apr 09 '21 at 15:42

1 Answers1

1

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"];
nachospiu
  • 2,009
  • 2
  • 8
  • 12
  • not using like this $data[1] $data[0] my question is what if there is more column in csv file how to get 'name' column ? im asking dynamically get name column – Bala Chandar Apr 09 '21 at 15:57
  • You say something like this `$found_key = array_search('45654', array_column($final_result, 'phone'));`? Return the array index where the phone number was found. – nachospiu Apr 09 '21 at 16:07