2011-01-28 159 views
0

我試過這個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; 
} 
+2

你的檢查是非常簡單:他們產生相同的輸出?如果是這樣,這是正確的。你也輸出(在這兩種情況下)非常形成的HTML。您將結束諸如`

+0

對於代碼評論有http://codereview.stackexchange.com/ – Htbaa 2011-01-28 16:00:32

回答

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