php讀取csv資料儲存到數組代碼

來源:互聯網
上載者:User
 代碼如下 複製代碼

$info=csvtoarray::open('teste.csv');
//echo '<pre>';
//print_r($info);
//echo '</pre>';
foreach ($info as $c)
 {
  echo '學號:'.$c[0];
  echo '姓名:'.$c[1];
  echo '年齡:'.$c[2];
  echo '身高:'.$c[3].'<br>';
 }
 

 final class csvtoarray{

  /**
   * 把csv檔案解析為一個數組返回
   *
   * @param string $file 要解析的csv檔案路徑
   * @param char $delimiter csv檔案裡的內容分隔字元 預設為;
   * @return array
   */
  public static function open($file, $delimiter = ';'){
   return self::ordenamultiarray(self::csvarray($file, $delimiter), 1);
  }

  private function csvarray($file, $delimiter)
  {
   $result = array();
   $size = filesize($file) + 1;
   $file = fopen($file, 'r');
   $keys = fgetcsv($file, $size, $delimiter);
   fseek($file,0);//這裡原來的沒有..自己加上..這樣能讀取到第一行的內容
   while ($row = fgetcsv($file, $size, $delimiter))
   {
    for($i = 0; $i < count($row); $i++)
    {
     if(array_key_exists($i, $keys))
     {
      $row[$keys[$i]] = $row[$i];
     }
    }
    print_r($row);
    $result[] = $row;
   }

   fclose($file);

   return $result;
  }
  private function ordenamultiarray($multiarray, $secondindex)
  {
   while (list($firstindex, ) = each($multiarray))
   $indexmap[$firstindex] = $multiarray[$firstindex][$secondindex];
   asort($indexmap);
   while (list($firstindex, ) = each($indexmap))
   if (is_numeric($firstindex))
   $sortedarray[] = $multiarray[$firstindex];
   else $sortedarray[$firstindex] = $multiarray[$firstindex];
   return $sortedarray;
  }
 }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.