0

データベースから取得しているタグの配列があり、タグをタグクラウドにエクスポートしています。私は単語の最初のインスタンスだけを取得することに固執しています。例えば:

$string = "test,test,tag,tag2,tag3";

$getTags = explode("," , $string);
  foreach ($getTags as $tag ){
     echo($tag);
   }

これにより、テストタグが2回出力されます。最初、私stristrは次のようなことをするために使用できると思いました:

  foreach ($getTags as $tag ){
      $tag= stristr($tag , $tag); 
        echo($tag);
   }

これは明らかにばかげたロジックであり、機能しませんstristr。最初のオカレンスを置き換えるだけのようです。したがって、「test123」のようなものは「test」を削除して「123」を返すだけです。正規表現ですが、その動的な例は見つかりませんでした。

ありがとう、
ブルック

編集: unique_array()静的文字列を使用している場合は機能しますが、各行のデータを取得するためにwhileループを使用しているため、データベースからのデータは機能しません。

    $getTag_data = mysql_query("SELECT tags FROM `news_data`");
if ($getTag_data)
{

   while ($rowTags = mysql_fetch_assoc($getTag_data))
   {
     $getTags = array_unique(explode("," , $rowTags['tags']));
        foreach ($getTags as $tag ){
        echo ($tag);
      }
   }
}
4

5 に答える 5

4

使用するarray_unique()

$string = "test,test,tag,tag2,tag3";

$getTags = array_unique(explode("," , $string));
foreach ($getTags as $tag ){
   echo($tag);
}
于 2009-11-25T22:12:25.843 に答える
2

単語を値としてではなく、辞書のキーとして使用します。

$allWords=array()
foreach(explode("," , $string) as $word)
  $allWords[$word]=true;
//now you can extract these keys to a regular array if you want to
$allWords=array_keys($allWords);

あなたがそれをしている間、あなたはそれらを数えることもできます!

$wordCounters=array()
foreach(explode("," , $string) as $word)
{
  if (array_key_exists($word,$wordCounters))
     $wordCounters[$word]++;
  else
     $wordCounters=1;
}

//word list:
$wordList=array_keys($wordCounters);

//counter for some word:
echo $wordCounters['test'];
于 2009-11-25T22:13:29.477 に答える
1

テーブルの各行には、次のようにコンマで区切られた複数のタグが含まれていると想定しています。

Row0: php, regex, stackoverflow
Row1: php, variables, scope
Row2: c#, regex

その場合は、これを試してください:

$getTag_data = mysql_query("SELECT tags FROM `news_data`");

//fetch all the tags you found and place it into an array (with duplicated entries)
$getTags = array();
if ($getTag_data) {
   while ($row = mysql_fetch_assoc($getTag_data)) {
     array_merge($getTags, explode("," , $row['tags']);
   }
}

//clean up duplicity
$getTags = array_unique($getTags);

//display
foreach ($getTags as $tag ) {
   echo ($tag);
}

これは効率的ではないことを指摘しておきます。

もう 1 つのオプション (既にここで説明) は、タグを配列キーとして使用することで、タグを簡単にカウントできるという利点があります。
次のようにできます。

$getTag_data = mysql_query("SELECT tags FROM `news_data`");

$getTags = array();
if ($getTag_data) {
   while ($row = mysql_fetch_assoc($getTag_data)) {
     $tags = explode("," , $row['tags']);
     foreach($tags as $t) {
       $getTags[$t] = isset($getTags[$t]) ? $getTags[$t]+1 : 1;
     }
   }
}

//display
foreach ($getTags as $tag => $count) {
   echo "$tag ($count times)";
}
  • このコードはテストされていないことに注意してください。これは、アイデアを理解するためのものです。
于 2009-11-25T23:55:44.370 に答える
0

私はphpのarray_uniqueがあなたが探しているものだと信じています:

http://php.net/manual/en/function.array-unique.php

于 2009-11-25T22:12:35.173 に答える
0

配列を反復処理する前にarray_unique関数を使用しますか? 重複する文字列をすべて削除し、独自の関数を返します。

于 2009-11-25T22:13:58.477 に答える