这是我想要实现的一个非常简单的例子:
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']。
答案 0 :(得分:1)
使用将数字与名称相关联的关联数组:
$types = array(1 => 'cake', 2 => 'muffin');
然后将其用作:
echo "$sender has bought a {$types[$type]}";
请注意,必须使用双引号将变量扩展到字符串中,而不是像代码中那样单引号。
答案 1 :(得分:1)
或者,如果您想从数据库中返回此内容:
$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.
}
答案 2 :(得分:0)
根据你的例子,我会使用这样的数组:
$items = array(
"1" => "cake",
"2" => "muffin"
);
然后这样做:
echo "$sender has bought a {$items[$type]}";