我在文本区域中有制表符分隔的文本(字符串)。例如,用户只需使用标题将SQL查询中的结果集直接粘贴到此文本区域中。
读取此输入并在php或javascript中转换为数组的理想方式是什么。我最终希望使用json_encode将其转换为json。
帮助赞赏!!
答案 0 :(得分:0)
这样的事情应该有效:
<?php
if ($_POST) {
$data = trim($_POST['pastedData']);
$tabDelimitedLines = explode("\r\n", $data);
$myArray = Array();
foreach ($tabDelimitedLines as $lineIndex => $line) {
$fields = explode("\t", $line);
foreach ($fields as $fieldIndex => $field) {
if ($lineIndex == 0) {
// assuming first line is header info
$headers[] = $field;
} else {
// put the other lines into an array
// in whatever format you want
$myArray[$lineIndex - 1][$headers[$fieldIndex]] = $field;
}
}
}
$json = json_encode($myArray);
echo "Associative Array in PHP:<br>";
echo "<pre>";
var_dump($myArray);
echo "</pre>";
echo "JSON:<br>";
echo $json;
echo "<br><br>";
}
?>
<html>
<form method="post">
<label>Paste some Tab Delimited Data with Headers:</label><br>
<textarea name="pastedData"></textarea><br><br>
<button type="submit">Submit</button>
</form>
</html>