Enjoy unlimited access to all forum features for FREE! Optional upgrade available for extra perks.

php help? (unique unserialize)

Status
Not open for further replies.
Joined
Jan 19, 2007
Posts
2,208
Reaction score
47
Need a bit of help with some php and a few kind members helped me in the past.

My code is:
PHP:
$query = "SELECT names FROM table WHERE type='$type'";
$result = mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_array($result)) { 
foreach(unserialize($row['names']) as $key => $value){ 
echo $value . '<br />'; 
} 
}

Basically, a field on my table is called names. The information in this field is serialized (so many names are together in a single field, for a single row).

I want to be able to search the whole table (where type='$type' - so many rows) for all names and then show unique names only.

My code above unserializes the names from each field and then lists them, but doesn't deal with any duplicates (which I need removing).

I have looked at functions like "unique_array()", and have tried using it in different places but it isn't doing the job.

Any help appreciated.
 
PHP:
$new_array = array();

while($row = mysql_fetch_array($result)) { 
    foreach(unserialize($row['names']) as $key => $value){ 
    //echo $value . '<br />'; 
    $new_array[] = $value
    } 
}

$unique_array = array_unique( $new_array );
var_dump( $unique_array );

Try this quick fix...
 
Many thanks for your reply jDubya.

I just took someone's advice on another forum and the following code worked:

PHP:
$names = array();
while($row = mysql_fetch_array($result)) { 
   $names = array_unique(array_merge($names, unserialize($row['names'])));
}
foreach($names as $value){ 
   echo $value . '<br />'; 
}

Will take a look at your code later. I love PHP but the more i learn the more i don't understand!

Appreciate your help.
 
Your welcome - one thing to keep in mind though is that a solution like this doesn't scale well so on a larger data set performance would degrade massively... If working with larger data sets the DB should be doing the work instead of PHP.

My problem when I first started learning PHP I wasn't properly shown Mysql - didn't learn for a long time things like EXPLAIN, INDEXES, DISTINCT(), DATE_SUB() etc instead of relying completely on PHP. Probably the single most useful period of learning I went through.

Good luck!
 
Status
Not open for further replies.

The Rule #1

Do not insult any other member. Be polite and do business. Thank you!

Featured Services

Sedo - it.com Premiums

IT.com

Premium Members

AucDom
UKBackorder
Be a Squirrel
Acorn Domains Merch
MariaBuy Marketplace

New Threads

Domain Forum Friends

Other domain-related communities we can recommend.

Our Mods' Businesses

Perfect
Service
Laskos
*the exceptional businesses of our esteemed moderators
Top Bottom