dongliufa6380 2019-06-06 20:01
浏览 143
已采纳

如何通过行和列值获取csv单元格值

I have a simple CSV table

Name,Year of birth,City
Yeremy,1980,New York
Louis,1982,Washington
Marta,1987,Chicago
David,1985,Los Angeles

Also, I have this code to can get cell value by number of row and number of column:

$trow = 3;
$tcolumn = 3;

$output .= '<span>';
$row = 1;
$mycsvfile = array();
if (($handle = fopen($abspath, "r")) !== FALSE) {
   while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
   $num = count($data);
   $row++;
   $mycsvfile[] = $data;.
   }
   fclose($handle);
}
$output .= $mycsvfile[$trowN][$tcolumnN];
$output .= '</span>';

I want to define that $trow=Marta and $tcolumn=City, so, in this case to get value "Chicago"...

  • 写回答

1条回答 默认 最新

  • doupingzhi9674 2019-06-06 20:11
    关注

    The code could be optimized a lot, but with the current code:

    $output .= array_column($mycsvfile, null, 0)['Marta'][2];
    
    • Re-index the array on the values in the Name (column 0)
    • Access the one with index Marta, getting the value in the City (column 2)

    You can access by column name if you combine the column names:

    if (($handle = fopen($abspath, "r")) !== FALSE) {
       $columns = fgetcsv($handle, 1000, ",");
    
       while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
           $mycsvfile[] = array_combine($columns, $data);
       }
       fclose($handle);
    }
    $output .= array_column($mycsvfile, null, 'Name')['Marta']['City'];
    

    Keep in mind that if Marta occurs more than once in the Name column then the LAST one will be returned.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算