2016-12-29 6 views
-4

テキスト領域にタブ区切りのテキスト(文字列)があります。例えば、ユーザはSQLクエリからの結果セットをヘッダーで直接このテキスト領域に貼り付けるだけです。タブで区切られたテキストを配列に変換する

この入力を読み、phpまたはjavascriptのいずれかの配列に変換する理想的な方法は何でしょうか。私は結局、これをjson_encodeを使ってjsonに変換したいと思っています。

ヘルプありがとう!

+3

http://stackoverflow.com/questions/1792950/explode-string-by-one-or-more-spaces-or-tabs – Jeff

+0

[ 'グーグルPHPタブ区切り文字列を配列に変換する」](http://stackoverflow.com/questions/16288589/converting-a-texttab-delimited-to-php-associative-array-instead-of-this-code) – Ghost

答えて

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> 
関連する問題