这种转换是否正确?

时间:2011-01-28 14:57:18

标签: php asp-classic

我尝试将此ASP代码转换为PHP,并想知道它是否正确:

ASP:

Set emp = Server.CreateObject("Scripting.Dictionary")

EM_GENERAL=0
EM_AUDIO=1
EM_VIDEO=2 

emp.Add EM_GENERAL, "General"
emp.Add EM_AUDIO, "Audio"
emp.Add EM_VIDEO, "Video"

For each em in Emp
Response.Write "<option value=" + CStr(em)
If em = CInt(IT_FIELD) Then
    Response.Write " selected"
End If
Response.Write ">"
Response.Write Emp.Item(em)
Next

PHP:

$EM_GENERAL=0;
$EM_AUDIO=1;
$EM_VIDEO=2;

$emp = array();
$emp[$EM_GENERAL] = "General";
$emp[$EM_AUDIO] = "Audio";
$emp[$EM_VIDEO] = "Video";

foreach ($emp as $em) {
  echo "<option value=" + ($em);
  if ($em == intval($IT_FIELD)) {
    echo " selected";
  }
  echo ">";
  echo $em;
}

1 个答案:

答案 0 :(得分:0)

在VB中,For Each循环遍历Dictionary键而不是值,因此在ASP代码中,em是emp条目的数字键。在PHP中,foreach遍历值,因此$em是值,而不是键。您的if ($em == intval($IT_FIELD))支票无法按预期运作。幸运的是,php foreach循环还支持语法foreach ($array as $key => $value),其中$value等同于Dictionary.Item(key)

请改为尝试:

foreach ($emp as $em => $value) {
  echo "<option value=" + ($em);
  if ($em == intval($IT_FIELD)) {
    echo " selected";
  }
  echo ">";
  echo $value;
}