...

View Full Version : Unique_array not outputting



Jacobb123
05-16-2008, 01:24 AM
I have the following code:



<? $genre1=mysql_query("SELECT genre FROM files");

$x=0;

$d=array();
while($genre=mysql_fetch_array($genre1)){

$findme=",";
$mystring= $genre['genre'];
$pos = strpos($mystring, $findme);

if($pos== true){

$arr=explode(',',$genre['genre']);
$darr=array_unique($arr);
$count=count($darr);
$i=0;
while($i < $count){
array_push($d,$darr[$i]);
$i++;
}

}

else { array_push($d,$genre['genre']); $d=array_unique($d); }

$x++;
}

echo '<select name="genre">';
$ud=array_unique($d);
$countd=count($ud);
$y=0;
while($y < $countd){
echo
'<option>'.$ud[$y].'</option>';
$y++;
}
echo
'</select>';

echo '<pre>';
print_r($ud);
echo '</pre>';


The output from the print_r($ud) gives me the following:

Array
(
[0] => genre
[2] => genre1
)


but in the option drop down I only get "genre" and a blank line below it.. What could be the issue

syosoft
05-16-2008, 09:03 AM
Holy sloppy code. ;) Lets clean it up first - keep in mind, this is fully untested but it appears to recreate what you're after. Notice how I'm storing the option as the key of the array, so I don't have to use array_unique everywhere - the options will just overwrite without harm.



<?php
$query_result = mysql_query("SELECT genre FROM files WHERE genre != ''");
$stored_options = array();
$count = 0;

while($record_set = mysql_fetch_assoc($query_result)) :
foreach(explode(',', $record_set['genre']) as $option) :
$stored_options[$option] = $count;
++$count;
endforeach;
endwhile;

echo '<select name="genre">';

foreach(array_flip($stored_options) as $option) :
echo '<option value="'.$option.'">'.$option.'</option>';
endforeach;

echo '</select>';
?>


Or you can take it 1 step further if you're running the query and outputting the select box (and don't need to do any sorting) on the same page (thou I wouldn't advise for maintenance reasons)...



<select name="genre" id="genre">
<?php
$query_result = mysql_query("SELECT genre FROM files WHERE genre != ''");
$stored_options = array();

while($record_set = mysql_fetch_assoc($query_result)) :
foreach(explode(',', $record_set['genre']) as $option) :
if(!in_array($option, $stored_options)) :
echo '<option value="'.$option.'">'.$option.'</option>';
$stored_options[] = $option;
endif;
endforeach;
endwhile;
?>
</select>


But keep in mind, this is a horrid coding practice.

Jacobb123
05-18-2008, 06:00 AM
Thanks for the reply. I know that my code is sloppy. I have to learn the hard way I think before I can code the easy way....It's my learning process. That's why I appreciate this forum so much because it allows people to critique my code and I get better. Thanks again



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum