PHPは配列から単語の最初の出現のみを取得します
-
05-07-2019 - |
質問
データベースからプルするタグの配列があり、タグクラウドにタグをエクスポートしています。単語の最初のインスタンスのみを取得することに固執しています。例:
$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
は最初の出現のみを置き換えるように思われるため、「test 123」 " 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);
}
}
}
解決
テーブルの各行には、次のように、コマで区切られた複数のタグが含まれていると想定しています:
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);
}
これは効率的ではないと指摘します。
別のオプション(既に説明した)は、タグを配列キーとして使用することです。タグを簡単にカウントできるという利点があります。
次のようにできます:
$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)";
}
- このコードはいずれもテストされていないことを覚えておいてください、それはあなたがアイデアを得るためです。
他のヒント
array_unique()
$string = "test,test,tag,tag2,tag3";
$getTags = array_unique(explode("," , $string));
foreach ($getTags as $tag ){
echo($tag);
}
単語を値としてではなく、辞書のキーとして使用します。
$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'];
phpのarray_uniqueはあなたが探しているものだと思います:
配列を反復処理する前に array_unique 関数を使用しますか?重複する文字列をすべて削除し、一意の関数を返します。
所属していません StackOverflow