문제

데이터베이스에서 가져 오는 태그 배열이 있는데 태그를 태그 클라우드로 내보내고 있습니다. 나는 단어의 첫 번째 사례 만 얻는 데 갇혀 있습니다. 예를 들어:

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

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

이것은 테스트 태그를 두 번 출력합니다. 처음에 나는 내가 사용할 수 있다고 생각했다 stristr 다음과 같은 작업을 수행하려면 :

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

이것은 분명히 어리석은 논리이며 작동하지 않습니다. stristr "Test 123"과 같은 것이 "테스트"를 제거하고 "123"을 반환 할 것입니다. 나는 이것도 Regex와 함께 할 수 있지만 역동적 인 exmaple을 찾지 못했습니다. 저것.

감사,
브룩

편집하다: 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가 당신이 찾고있는 것이라고 생각합니다.

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

사용 Array_unique 배열을 반복하기 전에 기능? 모든 중복 문자열을 제거하고 고유 한 기능을 반환합니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top