0

誰でも次のことを手伝ってもらえますか。mysql テーブル内に「notes」フィールドがありますが、それを新しいテーブルに分割する必要があります。

メモは現在、次の形式になっています。

2012/10/22 15:50 に username1 によって追加されました

メモはこちら

2012/10/20 12:29pm に username2 によって追加されました

ノートはこちらなど

例として、ここに 2 つのメモがあります。これを配列に入れるにはどうすればよいですか:

[0] => Array(
        [0] username1
        [1] 22/10/2012 3:50pm
        [2] Note1
    )
[1] => Array(
        [0] username2
        [1] 20/10/2012 12:29pm
        [2] Note2
    )

preg_split を使用してみましたが、メモ自体に「追加者」が含まれている可能性があるため、「追加者」を単独で使用して分割することはできないため、「日時にユーザー名によって追加された」場合にのみメモが返されます。

これを行う最良の方法は何ですか?

ありがとう

4

2 に答える 2

2

これを試して

// Get the data from the database
$myData = $row['notes'];

// Split this into an array
$data = explode("\r\n", $myData);

// $data has each line as an element of the array
$key   = -1;
$final = array();
foreach ($data as $element)
{
    // Check if this is the first row
    if (strpos($element, "Added by") > 0)
    {
        $key = $key + 1;
        // This is the first header row. Get the info from it
        $tmp   = str_replace("Added by", "", $element);
        $parts = explode(" on ", $tmp)

        // Add them to the final array
        // Username
        $final[$key][0] = trim($parts[0]);
        // Date
        $final[$key][1] = trim($parts[1]);

        // Initialize the note element
        $final[$key][2] = '';
    }
    else
    {
        // We don't have the 'Added On' so add this as a note.
        $final[$key][2] .= $element;
    }
}

これはあなたに取り組むための基盤を与えるはずです。notes要素の空行を確認することもできます$final[$key][2] .= $element;

于 2012-10-23T15:05:29.773 に答える
0

おそらくあなたの最善の策は、そのフィールドを行の配列に丸呑みしてから、各行を反復することです。行のように見えるものをヒットするとAdded、新しいレコードが作成され、後続の各行がメモの一部になります...別の追加された行をヒットするまで。

例えば

$lines = array(... your monolithic text here ...);
$idx = 0;
$notes = array();
foreach($lines as $line) {
   if (preg_match('/^Added by (.*?) on (.*?)$/', $matches)) {
        $notes[$idx] = array(
             0 => $matches[1], // username
             1 => $matches[2], // date/time
             2 => '' // note text
        )
        continue;
   }
   $notes[$idx[2]] .= $line;
}
于 2012-10-23T15:04:20.960 に答える