开发者

Explode array and assign as variables

I have a table in the following structure...

ID     USER_ID      INTEREST
1      290          soccer
2      290          tennis
3      290          badminton
4      560          netball

I want to grab all values from the table where the user id is equal to the session user id and assign them as variables.

I have the following which 开发者_开发知识库works but displays the data very peculiarly..

$interestsquery  = "SELECT * FROM user_interests WHERE user_id = " . $usersClass->userID();
$result = mysql_query($interestsquery);

while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
 $interests[] = $row['interest'];
 $interest1 = $interests[1];
 $interest2 = $interests[2];
 $interest3 = $interests[3];

 print $interest1 . " - " . $interest2 . " - " . $interest3;

} 

The above however outputs something along the lines of...

- - tennis - - tennis - badminton - 

Can anybody see where I'm going wrong?


This should do what you need:

$interestsquery  = "SELECT `interest` FROM `user_interests` WHERE `user_id` = " . $usersClass->userID();
$result = mysql_query($interestsquery);

$interests = array();
while(list($interest) = mysql_fetch_array($result))
    $interests[] = $interest;

print explode($interests, ' - ');


Think what happens to your loop at the first iteration:

  • $interest is an empty array
  • you fetch the first value and put it into $interest[0],
  • you fill $interest1 with the value that lies into $interest[1] (it is empty)
  • same for $interest2 and $interest3
  • you print ""." - ".""." - ".""

in the second run:

  • $interest is [0=>soccer]
  • you fetch the second value and put it into $interest[1],
  • you fill $interest1 with the value that lies into $interest[1] tennis
  • same for $interest2 and $interest3 (that are still empty)
  • you print "tennis"." - ".""." - ".""

and so on.

You need print the result when you exit the while loop (and the code is still flawed as it don't get the value into the index 0 of the array).

An alternative should be:

$interestsquery  = "SELECT `interest` FROM `user_interests` WHERE `user_id` = " 
                 . $usersClass->userID();
$result = mysql_query($interestsquery);

$interests = array();
// you fetch just a field, fetch_row will be sufficent
while($interest = mysql_fetch_row($result)) {
    array_push($interests, $interest[0]);
}
echo implode(' - ', $interests);


$interests = array();

while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
  $interests[] = $row['interest'];
}

$int_count = count($interests);
$i=0;

foreach ($interests as $interest) {
    $var = 'interest' . ($i + 1);
    $$var = $interest;
    $i++;
} 

print $interest1 . " - " . $interest2 . " - " . $interest3;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜