2017-04-08 39 views
0

我試着去檢查了agianst一個數組,我的代碼如下陣列檢查不完整的數據

$coax = array("86.52", "85.218", "178.155", "212.10", "212.112", "62.107", "5.206"); 


    if(in_array("86.52.16.14", $coax)) 
      { 
       echo "jubii"; 
        } else 
        { 
        echo "nej nej nej"; 
        } 
     } 

但我的問題是,我在檢查XX.XX.XX.XX對XX.XX陣列。有沒有解決這個問題的方法?

+0

你是什麼意思,必須檢查xx.xx.xx.xx對xx.xx?顯然這些不匹配。 – pvg

+0

你總是在開始時匹配嗎?或者它應該與數組中的「16.14」匹配? – Barmar

+0

它是因爲我從csv中取ip,而且IP是完整的xx.xx.xx.xx但是我只有數組中的範圍的開始,並且我想檢查ip是否與該範圍匹配。 –

回答

0

循環遍歷數組,測試輸入IP是否以數組元素開始。

$found = false; 
foreach ($coax as $x) { 
    if (strpos("86.52.16.14", $x) === 0) { 
     $found = true; 
     break; 
    } 
} 

if ($found) { 
    echo "jubii"; 
} else { 
    echo "nej nej nej"; 
} 
-1

你可能會爆炸了每個數組的第一個兩件,並檢查它針對同軸電纜陣列像這樣:

$coax = array("86.52", "85.218", "178.155", "212.10", "212.112", "62.107", "5.206"); 
$checkValue = "86.52.16.14"; 
$tempArray = explode(".",$checkValue); 
$checkValueFormatted = $tempArray[0] .".".$tempArray[1]; 

if(in_array($checkValueFormatted, $coax)) 
      { 
       echo "jubii"; 
        } else 
        { 
        echo "nej nej nej"; 
        } 
     } 
} 

如果你把$校驗值的數組,你可以在這一個foreach扔並一次檢查多個值。你也可以扔在foreach,所以你可以像這樣更快地檢查多個值...

$coax = array("86.52", "85.218", "178.155", "212.10", "212.112", "62.107", "5.206"); 
    $checkValues = array("86.52.16.14", "42.12.1231.1231", "212.10.123.123"); 

    foreach ($checkValues as $value) { 

    $tempArray = explode(".",$value); 
    $checkValueFormatted = $tempArray[0] .".".$tempArray[1]; 
    if(in_array($checkValueFormatted, $coax)) 
       { 
        echo "jubii"; 
         } else 
         { 
         echo "nej nej nej"; 
         } 
      } 
    } 
}