2016-12-29 91 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> 
相關問題