简体   繁体   中英

array_unique only on one field?

I have following code for an autocomplete box, I'm adding an image for choice clarification but want to make sure the title returned is unique, but, when I get to the code which makes the array unique, i've added other code which makes it non unique in other areas. Is there a way around this?

$query = "SELECT $title, imageURL FROM PRprodINFO2 WHERE ((prodcatID = '$cat_id')
          AND ($title LIKE \"%" . $_GET["q"] . "%\")) group by $title LIMIT 8";
}

$result = mysql_query($query);

// set the array
$output_items = array();

while($row = mysql_fetch_array($result)) { 

    // clean after first non letter/number
    $row[$title] = preg_replace('/[^\w\s].*$/', "", $row[$title]);

    //trim spaces
    $row[$title] = trim($row[$title]);

    // add image src
    $output_items[] = '<img src='.$row[imageURL].' style=max-width:50px;>'
                      .$row[$title]; 

} // while

// here i need just $row[title] to be unique,
// it is made non unique after regex strips off some characters
$output = array_unique($output_items);

print(implode("\n", $output));

mysql_close();

I am possibly confused by what you are asking. It seems like you would already have unique titles since you are grouping by title in your sql. But, maybe you have extra non alpha-numeric characters you are stripping out with your regex that makes some unique titles the same.

In that case, instead of building up your $output_items like you are, try:

$output_items[$row['title']] = $row['imageURL'];

This will ensure that each title is unique. You will have the imageURL of the last row that matched that title. If you want, instead, the first title that matched, then just check isset before overwriting it like:

if (!isset($output_items[$row['title']])) $output_items[$row['title']] = $row['imageURL'];

Then, outside of the loop, build up your output string.

$output = '';
foreach ($output_items as $title => $image) {
    $output .= '<img src='.$image.' ...>'.$title."\n";
}
echo $output;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM