Jump to content

Displaying unique words


tully87

Recommended Posts

I'm trying to search a "keywords" field in a Microsoft Access database which can contain more than one word. E.g. "Cat", "Dog", "Cat Dog" etc. All of the keywords will then be listed on a page and when clicked will display any record containing that keyword. The problem I'm having is getting only one isntance of each word displayed and cannot figure out how to do it. So with the example "Cat", "Dog", "Cat Dog", "Mouse Dog" the only listed words should be "Cat" "Dog" "Mouse".

 

When using the following code:

 

<?php

$items = odbc_exec($odbc, "SELECT keywords FROM faq WHERE visible = 'true'") or die (odbc_errormsg());

 

while ($detail = odbc_fetch_array($items))

{

$exploded = explode(" ",$detail['keywords']);

$unique = array_unique($exploded);

 

foreach($unique as $unique)

{

var_dump($unique);

}

                }

?>

 

It returns:

string(0) "" string(0) "" string(0) "" string(0) "" string(0) "" string(3) "Dog" string(3) "Cat" string(3) "Dog" string(3) "Cat" string(3) "Dog" string(3) "Cat" string(5) "Mouse" string(3) "Cat" string(3) "Dog"

 

I've attached a word document of other examples I have tried but with no luck  :(

 

If anyone can provide any help I'd really appreciate it. Many thanks

 

[attachment deleted by admin]

Link to comment
https://forums.phpfreaks.com/topic/240304-displaying-unique-words/
Share on other sites

<?php
   $items = odbc_exec($odbc, "SELECT keywords FROM faq WHERE visible = 'true'") or die (odbc_errormsg());
         
   while ($detail = odbc_fetch_array($items))
   {   
      $exploded = explode(" ",$detail['keywords']);
      $unique = array_unique($exploded);
               
      foreach($unique as $unique)
      {
         var_dump($unique);
      }   
                }
?>

maybe something like this (comments explain my logic. Untested code off the top of my head)

<?php
// added a 'distinct' clause, just because there's no point in pulling out duplicates
   $items = odbc_exec($odbc, "SELECT distinct keywords FROM faq WHERE visible = 'true'") or die (odbc_errormsg());     
   // start my empty string
   $kwords = '';
   while ($detail = odbc_fetch_array($items)){
   		// I'm assuming database can return more than one result,
   		// so I'm ading them all in a string first
     	$kwords .= " ".$detail['keywords'];
   }
   // explode all words into single array
   $allWords = explode('',$kwords);
   // get unique words
   $unique = array_unique($allWords);
   // show me
   echo '<pre>';
   print_r($unique);
   echo '</pre>';
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.