简体   繁体   中英

Grabbing array from database, then getting information using each array value

totally stumped in this, basically I'm getting a comma seperated list from a user table, using it as an array and then using each value in the array to fetch data from a different table and output then.

$award_array = array($user_class->awards);
foreach($award_array as $award) {
    $getaward = mysql_query("SELECT `name`, `text`, `image` FROM `awards_av` WHERE `id` = '".$award."'");
    $awardstuff = mysql_fetch_array($getaward);
    echo "<img src='".$awardstuff['image']."' alt='".$awardstuff['name']."' title='".$awardstuff['text']."' />";
}

This is only giving out the first number in the array ($user_class->awards in this case is 1,2,3,4,5,6)

Any help is much appreciated!

I think I see the problem. You cannot simply take a string of a comma separated list, and throw it inside an array() tag and expect it to automatically convert it to an array. You must use the explode() function to do that.

What you're trying to do:

<?php
$string = 'a,b,c,d,e';
$myarray = array($string);
foreach ($myarray as $k => $v) {
    print $v .'<br />';
}
?>

Except that doesn't work. You need to convert the comma-separated list of values (which is a string) into an array, but you don't use array() to do that. You use PHP's built-in function called explode() -> http://php.net/explode like this...

<?php
$string = 'a,b,c,d,e';
$myarray = explode(',' $string);
foreach ($myarray as $k => $v) {
    print $v .'<br />';
}
?>

I think that is the problem you're having

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