dongsui0929 2015-02-25 07:09
浏览 66
已采纳

在php中读取CSV时,在所有数组中实现第一个数组键

if (move_uploaded_file($uploadData['tmp_name'], $uploadPath)) {
            $files = fopen($uploadPath, 'r');
            while (($line = fgetcsv($files, 0, ",")) !== FALSE) {
            //$line = array_combine($line,$line); try but not working
            pr($line);
            }
}

I am getting output like that -

Array
(
    [Company Name] => Company Name
    [Primary First] => Primary First
    [Primary Last] => Primary Last
)
Array
(
    [0] => Naturfrisk Energy Bar
    [1] => Aksel
    [2] => Romer
)
Array
(
    [0] => The Code Devloper
    [1] => vikas
    [2] => Tyagi
)

But i need Output like that-

Array
(
    [Company Name] => Company Name
    [Primary First] => Primary First
    [Primary Last] => Primary Last
)
Array
(
    [Company Name] => Naturfrisk Energy Bar
    [Primary First] => Aksel
    [Primary Last] => Romer
)
Array
(
    [Company Name] => The Code Devloper
    [Primary First] => vikas
    [Primary Last] => Tyagi
)
  • 写回答

2条回答 默认 最新

  • dongluolie3487 2015-02-25 07:22
    关注

    I think you should store first array returned by fgetcsv for keys for later arrays as the first line would be header line and you want to use that for keys in subsequent arrays being returned.

    So something like this would work

    if (move_uploaded_file($uploadData['tmp_name'], $uploadPath)) {
                $files = fopen($uploadPath, 'r');
                $lineNo = 1;
                while (($line = fgetcsv($files, 0, ",")) !== FALSE) {
                    if($lineNo == 1)
                       $arrHeader = $line;
                    else
                       $line = array_combine($arrHeader, $line);
    
                    pr($line);
                    $lineNo++;
                }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀