Last active
November 16, 2019 04:52
-
-
Save syuji-higa/c47c182b22ebd4047aa4c118b39b1b7b to your computer and use it in GitHub Desktop.
PHP - search CSV view
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
setlocale(LC_ALL, 'ja_JP.UTF-8'); | |
function get_csv_search_to_map($csv, $search_key, $search_val) { | |
$csv = ereg_replace("\r\n|\r|\n", "\n", $csv); | |
$csv = mb_convert_encoding($csv, 'UTF-8', 'sjis-win'); | |
$temp = tmpfile(); | |
$meta = stream_get_meta_data($temp); | |
fwrite($temp, $csv); | |
rewind($temp); | |
$file = new SplFileObject($meta['uri']); | |
$file -> setFlags(SplFileObject::READ_CSV); | |
$map = array(); | |
$keys = array(); | |
$isIdLine = false; | |
$search_index = null; | |
foreach($file as $row_index => $line) { | |
if($row_index === 0) { | |
foreach($line as $kyes_index => $val) { | |
$keys[] = $val; | |
if($search_key === $val) { | |
$search_index = $kyes_index; | |
} | |
} | |
} else { | |
foreach($line as $col_index => $val) { | |
if($search_index === $col_index && $search_val === $val) { | |
$isIdLine = true; | |
} | |
if(!$isIdLine) continue; | |
$map[$keys[$col_index]] = $val; | |
} | |
if($isIdLine) break; | |
} | |
} | |
fclose($temp); | |
$file = null; | |
return $map; | |
} | |
if(!isset($_GET['id'])) exit; | |
$id = $_GET['id']; | |
$csv_data = file_get_contents('data.csv', "id,name,age\n0,taro,20,\n1,jiro,25,\n2,saburo,30"); | |
$data = get_csv_search_to_map($csv_data, 'id', $id); | |
if(empty($data)) exit; | |
?> | |
<!DOCTYPE html> | |
<html lang="ja"> | |
<body> | |
<li>ID: <?php echo $data['id'] ?></li> | |
<li>Name: <?php echo $data['name'] ?></li> | |
<li>Age: <?php echo $data['age'] ?></li> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment