2014-12-30 54 views
1

以零開頭的郵政編碼第一位數下面的PHP代碼應返回的$zone 5.與$postcodeprefix應該是075.如何獲得PHP

我相信,因爲PHP是治療的郵政編碼這是不工作作爲整數而不是字符串。我試過這樣的東西:

$postcode = $postcode." "; 
$postcode = strval($postcode); 

我嘗試過的東西都沒有工作。

什麼是修復?

$postcode = 07558;//comes from database as a number. I can't change this. 
$postcode = $postcode." "; //one of various ways I have tried to turn this into a string 
$postcode = trim($postcode); 

$zone = 99; 
$postcodeprefix = substr($postcode,0,3); 
echo "\$postcodeprefix=".$postcodeprefix."\n"; 
$postcodeprefixkey = substr($postcode,0,1); //this is the first postcode digit 
echo "\$postcodeprefixkey=".$postcodeprefixkey."\n"; 
if ($postcodeprefixkey == 0) { 
       //any range containing postcode which starts with 0 
       if ($postcodeprefix >= 001 && $postcodeprefix <= 005) {$zone = 5;} else 
       if ($postcodeprefix >= 006 && $postcodeprefix <= 009) {$zone = 6;} else 
       if ($postcodeprefix >= 010 && $postcodeprefix <= 029) {$zone = 5;} else 
       if ($postcodeprefix >= 030 && $postcodeprefix <= 054) {$zone = 6;} else 
       if ($postcodeprefix >= 055 && $postcodeprefix <= 055) {$zone = 5;} else 
       if ($postcodeprefix >= 056 && $postcodeprefix <= 059) {$zone = 6;} else 
       if ($postcodeprefix >= 060 && $postcodeprefix <= 098) {$zone = 5;} 
      } 
echo "\$zone=".$zone; 
+0

$ postcode =(string)$ postcode; – Slime

+0

@slime - 那不行。我嘗試過這個。 – MountainX

+0

郵政編碼是字符串,而不是數字。 – Brad

回答

0

的問題是在這條線:

$postcode = 07558;//comes from database as a number. I can't change this. 

在這裏,$郵編已經是一個八進制值和

$postcode = 07558;//comes from database as a number. I can't change this. 
$postcode = $postcode." "; //one of various ways I have tried to turn this into a string 
$postcode = trim($postcode); 

echo $postcode; 

給493

把它作爲一個號碼,這很容易:

$postcode = 7558; // 07558 would be treated as octal value! 

$postcodeC = intval($postcode/100); // 075 

if ($postcodeC < 100) 
{ 
     ... 
     if ($postcodeC >= 60 && $postcodeC <= 98) {$zone = 5;} 
     ... 
} 
+0

這不起作用。你可以在這裏查看:http://writecodeonline.com/php/。而不是像你在評論中預期的那樣使用075,你實際上得到了4. 07558在PHP中被當作八進制數。我寧願使用字符串。 – MountainX

+0

是的,那是因爲PHP將'$ postcode = 07558;'解釋爲八進制值,而不是以10爲基數。我改變了上述內容。 –

+0

正如我在我的問題中提到的,我無法更改數據庫中的數據。所以我無法從郵政編碼中刪除前導零,我也不想那樣做。它會在代碼的其他部分產生尺寸效果。 – MountainX

0

下面是我最終如何解決它。我欺騙了substr()函數,不用用這種技術將$ postcode重新解釋爲八進制數字:

 $postcodeprefix = substr("x".$postcode,1,3); 
     $postcodeprefixkey = substr("x".$postcode,1,1);