8
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHPでCSVを配列にする

Posted at

やりたいこと

名前,バイエル符号,等級,地球からの距離 
Sirius,α CMa,−1.46,8.6
Canopus,α Car,−0.74,310
Rigil Kentaurus,	α Cen,−0.27 (0.01 + 1.33),4.4
Arcturus,α Boo,−0.05,37
Vega,α Lyr,25,0.03 (−0.02 - 0.07var)

のようなヘッダー付きのCSVから本体だけを切り取って行ごとに配列に直し、

var_dump($row_array);

すると

array(4) {
  [0]=>
  string(6) "Sirius"
  [1]=>
  string(6) "α CMa"
  [2]=>
  string(7) "−1.46"
  [3]=>
  string(4) "8.6
"
}

となるようにしたい。

コード


<?php

// ファイルの中身を配列で取得.
$csv = file('/Users/863/Desktop/php_files/stars.csv');

// ヘッダーを切り取る.
$csv_header = $csv[0]; 
$csv_body = array_splice($csv, 1);

// 各行を配列に直す.
foreach ($csv_body as $row) {
  $row_array = explode(',', $row);
  var_dump($row_array);
  // 処理
}

使った関数

8
15
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?