LoginSignup
0
2

More than 3 years have passed since last update.

【PHP】TSVファイルを配列に変換する

Posted at

webサイトなどでカテゴリを設定・呼び出す際に必要なときがちょいちょいあるかと思います。

環境

PHP 7.3.18

tsvデータ例

スプレッドシートなどで下記のような表を作成
※一番左の列に項目を、右に列でデータを追加していく

~/config/member.tsv

name 田中 斎藤
id tanaka saito
email tanaka@~ saito@~
age 24 31
from tokyo saitama

実装

hash.php
toHash(~/config/member.tsv,"\t");

function toHash($filePath,  $format = false, $first = false)
{
    //formatはtsvしか許可しない
    if (!($format == "\t")) {
        return false;
    }

    //ファイルの存在判定
    if (!file_exists($filePath)) {
        return false;
    }

    $fl = file($filePath);
    $data = array();
    foreach ($fl as $k => $v) {
        $column = explode($format,  $v);
        if ($k == 0) {
            foreach ($column as $i => $j) {
                $title[$i] = trim($j);
            }

            if ($first == false) {
                continue;
            }
        }

        foreach ($column as $i => $j) {
            if ($i == 0) {
                $key = $j;
            } else {
                $data[$key][$title[$i]] = trim($j);
            }
        }
    }
    return $data;
}

結果

array(4) {
  ["id"]=>
  array(2) {
    ["田中"]=>
    string(6) "tanaka"
    ["斎藤"]=>
    string(5) "saito"
  }
  ["email"]=>
  array(2) {
    ["田中"]=>
    string(6) "tanaka"
    ["斎藤"]=>
    string(5) "saito"
  }
  ["age"]=>
  array(2) {
    ["田中"]=>
    string(2) "24"
    ["斎藤"]=>
    string(2) "31"
  }
  ["from"]=>
  array(2) {
    ["田中"]=>
    string(5) "tokyo"
    ["斎藤"]=>
    string(7) "saitama"
  }
}

各行ごとに配列で返ってきます。

0
2
0

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
0
2