2015-05-03 76 views
-6

我試圖將Python中的腳本轉換爲PHP。它沒有工作。將Python轉換爲PHP

def getL5(iValue,Pvalue): 
PixelNoise = open(Pvalue + '.txt','r') 
l5 = {} 
Ivalue = int(iValue) % 10000 
p_x = Ivalue % 100 
p_y = int(math.floor(Ivalue/100)) 
for iValue in PixelNoise: 
    pixel,value = iValue.strip().split(':') 
    l5[pixel] = value 
PixelNoise.close() 
return l5[str(p_x)+','+str(p_y)] 

以上是Python。

public function getL5($iValue,$Pvalue) { 
$PixelNoise = fopen($Pvalue.'.txt', "r"); 
$L5 = array(); 
$Ivalue = intval ($iValue) % 10000; 
$p_x = $Ivalue % 100; 
$p_y = intval(floor($Ivalue/100)); 
foreach ($PixelNoise as $iValue){ 
    $temp= explode(':', $iValue); 
    $pixel=$temp[0]; 
    $value=$temp[1]; 
    $L5[$pixel] = $value; 
} 
fclose($PixelNoise); 
return $L5[(string)$p_x.','.(string)$p_y]; 
} 

以上是我的PHP代碼。它錯在哪裏?

+0

你會得到什麼錯誤? – yantrakaar

+3

請注意,python中有一個'strip',你在PHP中沒有這樣做。不知道這是否會導致問題,因爲你沒有說出症狀。你真的認爲「不起作用」是有幫助的診斷嗎? – cdarke

回答

1

PHP無法通過文件行進行foreach。一個普遍的選擇是使用fgets的while循環。

function getL5($iValue,$Pvalue) { 
    $PixelNoise = fopen($Pvalue.'.txt', "r"); 
    $L5 = array(); 
    $Ivalue = intval ($iValue) % 10000; 
    $p_x = $Ivalue % 100; 
    $p_y = intval(floor($Ivalue/100)); 
    if ($PixelNoise) { 
     while ($iValue = fgets($PixelNoise)) { 
      $temp= explode(':', trim($iValue)); 
      $pixel=$temp[0]; 
      $value=$temp[1]; 
      $L5[$pixel] = $value; 
     } 
     fclose($PixelNoise); 
    } 
    else { 
    print "There was an error opening the file."; 
    // You might want to do some error handling here 
    // e.g. trigger an error, or make this function return false. 
    } 
    return $L5[(string)$p_x.','.(string)$p_y]; 

}

爲了保持一致性,你也可以用strval()就像INTVAL()而不是鑄造。此外FYI編碼風格並不是PHP開發人員會喜歡閱讀的內容,請考慮perusing this advice