简体   繁体   中英

How to echo variable depending on specific field in table?

Here's a very simplified example of what I am trying to achieve :

GIFT
sender  |  type
phil    |  1
phil    |  2

Here, 1 = cake and 2 = muffin.

$table = query("SELECT sender, type FROM users WHERE sender = Phil");
foreach ($table as $row) {
$sender = $row['sender'];
$type = $row['type'];

echo '$sender has bought a $type';
}

This will output :

Phil has bought a 1
Phil has bought a 2 

How can I get the below output instead ?

Phil has bought a cake
Phil has bought a muffin

Should I use an array ?

 $type = array(
 1 => 'cake',
 2 => 'muffin'
 );

The problem is $type is already defined as $row['type'].

Use an associative array that relates numbers to names:

$types = array(1 => 'cake', 2 => 'muffin');

Then use it as:

echo "$sender has bought a {$types[$type]}";

Note that you must use doublequotes for variables to be expanded inside the string, not singlequotes as in your code.

Or if you'd like to return this from database:

$table = query("SELECT sender, 
                case when type = '1' then 'cake' 
                     when type = '2' then 'muffin'
                end as type 
                FROM users WHERE sender = Phil");

foreach ($table as $row) {
  $sender = $row['sender'];
  $type = $row['type'];

  echo "$sender has bought a $type"; //Use double quotes for $sender and $type to be interpolated.
}

Given your example, I would use an array like this:

$items = array(
    "1" => "cake",
    "2" => "muffin"
);

Then do this:

echo "$sender has bought a {$items[$type]}";

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