結果セットのフィールドに表示される単一の単語をカウントするにはどうすればよいですか?
例
id| マイフィールド 1 | 梨 りんご もも スイカ 2 | ライム ブドウ ナシ スイカ
個性的な言葉が6つあるから6つゲットしたい
高速なクエリは必要ありません。めったに実行されない単なる統計計算です。
ありがとう!
function uniqueWords ($result, $field) {
$words = array();
while ($row = mysql_fetch_assoc($result)) { /* or something else if you use PDO/mysqli/some ORM */
$tmpWords = preg_split('/[\s,]+/', $row[$field]);
foreach ($tmpWords as $tmpWord) {
if (!in_array($tmpWord, $words))
$words[] = $tmpWord;
}
}
return count($words);
}
結果をスペースで分割してから、次のように配列に追加できます。
foreach($results as $result)
{
$words = explode(" ", $result['myfield']);
$array = array();
foreach($words as $word)
$array[$word] = true;
}
echo count($array);
おそらくより良い方法ですが、これは迅速で汚いです
純粋な SQL ソリューションは考えられません。MySQL は単一の行を多数に分割することをあまり好みません。
ただし、PHP バージョンは簡単です。
$sql="CREATE TEMPORARY TABLE words (word VARCHAR(100) PRIMARY KEY)";
//run this according to your DB access framework
$sql="SELECT myfield FROM mytable";
//run this according to your DB access framework
while (true) {
//fetch a row into $row according to your DB access framework
if (!$row) break;
$words=preg_split('/[\s,]+/',$row['myfield']);
foreach ($words as $word) {
//Escape $word according to your DB access framework or use a prepared query
$sql="INSERT IGNORE INTO words VALUES('$word')";
//run this according to your DB access framework
}
}
$sql="SELECT count(*) AS wordcount FROM words";
//run this according to your DB access framework, the result is what you want
$sql="DROP TABLE words";
//run this according to your DB access framework