繁体   English   中英

如何根据表中的特定字段回显变量?

[英]How to echo variable depending on specific field in table?

这是我要实现的目标的非常简化的示例:

GIFT
sender  |  type
phil    |  1
phil    |  2

在这里,1 =蛋糕,2 =松饼。

$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';
}

这将输出:

Phil has bought a 1
Phil has bought a 2 

我怎样才能得到下面的输出呢?

Phil has bought a cake
Phil has bought a muffin

我应该使用数组吗?

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

问题是$ type已经定义为$ row ['type']。

使用将数字与名称相关联的关联数组:

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

然后将其用作:

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

请注意,必须使用双引号将变量扩展到字符串内,而不是像代码中那样将单引号引起来。

或者,如果您想从数据库中返回它:

$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.
}

给定您的示例,我将使用如下数组:

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

然后执行以下操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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