1

这是我想要实现的一个非常简化的示例:

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']。

4

3 回答 3

1

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

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

然后将其用作:

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

请注意,对于要在字符串内展开的变量,您必须使用双引号,而不是代码中的单引号。

于 2013-08-25T02:34:50.510 回答
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.
}
于 2013-08-25T02:41:33.767 回答
0

鉴于您的示例,我将使用这样的数组:

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

然后这样做:

echo "$sender has bought a {$items[$type]}";
于 2013-08-25T02:34:11.193 回答