Tan
Tan

Reputation: 33

Sorting output from mysql using the sort order of an inputted array

Just learning this stuff, so bear with any ignorance...

In what I'm trying to do, users input a word and as output receive their word as letter artwork that I've stored in a mysql database. I have a php page that breaks the characters of this word into an array and then matches these letter characters with tagged records.

What I'm having trouble with is getting the outputted images (a) into the same order as the characters of the user-inputted word and (b) choosing (randomly) only one tagged image (among many) per input letter.

Thanks for any suggestions or help on scripting this!


Here are some ideas I've cobbled together with some help...

$cxn = mysqli_connect($host, $user, $password, $database) or die("no cxn"); 
$lettertype = str_split($_POST['letter']);
array_walk($lettertype, 'mysql_real_escape_string');
$lettertype = "'" . implode("','", $lettertype) . "'";
$query = "SELECT * FROM images WHERE letter IN ($lettertype)";
$result = mysqli_query($cxn, $query)
        or die ("No good");
    while($row = mysqli_fetch_assoc($result))
        {
        echo "<a href='../delete3/images/{$row['imagePath']}' border='0'>
        <img src='../delete3/images/{$row['imagepath']}' width='100' height='80'/></a>";
        }

Upvotes: 0

Views: 189

Answers (1)

Scuzzy
Scuzzy

Reputation: 12332

You will have to test this yourself...

$alphasoup = array();
while($row = mysqli_fetch_assoc($result))
{
  $alphasoup[$row['letter']][] = $row;
}
foreach(str_split($_POST['letter']) as $alpha)
{
echo "<a href='../delete3/images/{$alphasoup[($alpha][0]['imagePath']}' border='0'>
<img src='../delete3/images/{$alphasoup[$alpha][0]['imagepath']}' width='100' height='80'/></a>";
}

Bonus Edit: and if you want the ability to have multiple graphics for the same letter and to pick one at random, store...

$alphasoup[$alpha][array_rand($alphasoup[$alpha])]['imagepath']

...as single variable to re-use in both instances in your string

Upvotes: 1

Related Questions