2014-06-11 56 views
1

我根據運輸方法獲得不同的文本字符串。例如一個訂單可以返回下列任何一項:基於文本的php陣列和數組映射

productmatrix_Pick-up_at_Store 
productmatrix_Standard 
productmatrix_3-Day_Delivery 
productmatrix_Pick-up_at_Store_-_Rush_Processing 
productmatrix_2-Day_Delivery 
productmatrix_1-Day_Delivery_-_Rush_Processing 

我也有一個「地圖」的生產代碼,我需要配合到這些。關鍵是要匹配的文字。價值是我需要的。地圖看起來是這樣的:

$shipToProductionMap = array(
    "1-day" => 'D', 
    "2-day" => 'E', 
    "3-day" => 'C', 
    "standard" => 'Normal', 
    "pick-up" => 'P' 
); 

我的目標是創建一個將返回從$shipToProductionMap基於我傳遞給它的字符串正確的值的函數。喜歡的東西:

function getCorrectShipCode($text){ 
if(strtolower($text) == if we find a hit in the map){ 
    return $valueFromMap; 
} 
} 

因此,舉例來說,如果我這樣做,我會得到P作爲返回值:

$result = getCorrectShipCode('productmatrix_Pick-up_at_Store'); 
//$result = 'P'; 

如何是最好的辦法做到這一點?

+0

這似乎是一個非常hacky的方式來解決這個問題。您是否無法控制訂單信息如何發送進行處理?爲什麼要傳遞字符串而不是對象或數組,這些對象或數組通過一些字符串比較解決方法精確地告訴您需要知道的內容? –

回答

0

好的,這裏有一個工作函數叫做getCorrectShipCode,它使用preg_match來比較船上的數組鍵值和生產映射,以便與傳遞給它的字符串進行比較。我把它通過所有的值中的一個測試陣列&所有作品作爲滾動概述:

// Set the strings in a test array. 
$test_strings = array(); 
$test_strings[] = 'productmatrix_Pick-up_at_Store'; 
$test_strings[] = 'productmatrix_Standard'; 
$test_strings[] = 'productmatrix_3-Day_Delivery'; 
$test_strings[] = 'productmatrix_Pick-up_at_Store_-_Rush_Processing'; 
$test_strings[] = 'productmatrix_2-Day_Delivery'; 
$test_strings[] = 'productmatrix_1-Day_Delivery_-_Rush_Processing'; 

// Roll through all of the strings in the test array. 
foreach ($test_strings as $test_string) { 
    echo getCorrectShipCode($test_string) . '<br />'; 
} 

// The actual 'getCorrectShipCode()' function. 
function getCorrectShipCode($text) { 

    // Set the ship to production map. 
    $shipToProductionMap = array(
     "1-day" => 'D', 
     "2-day" => 'E', 
     "3-day" => 'C', 
     "standard" => 'Normal', 
     "pick-up" => 'P' 
); 

    // Set the regex pattern based on the array keys in the ship to production map. 
    $regex_pattern = '/(?:' . implode('|', array_keys($shipToProductionMap)) . ')/i'; 

    // Run a regex to get the value based on the array keys in the ship to production map. 
    preg_match($regex_pattern, $text, $matches); 

    // Set the result if there is a result. 
    $ret = null; 
    if (array_key_exists(strtolower($matches[0]), $shipToProductionMap)) { 
    $ret = $shipToProductionMap[strtolower($matches[0])]; 
    } 

    // Return a value. 
    return $ret; 

} // getCorrectShipCode 
1

您可以使用foreachstripos相匹配的場景。

echo getCorrectShipCode('productmatrix_2-Day_Delivery'); 

function getCorrectShipCode($text){ 

    $shipToProductionMap = array(
        "1-day" => 'D', 
        "2-day" => 'E', 
        "3-day" => 'C', 
        "standard" => 'Normal', 
        "pick-up" => 'P' 
    ); 

    foreach($shipToProductionMap as $key => $value) 
    { 

     if(stripos($text, $key) !== false) 
     { 

      return $value; 

      break; 
     } 
    } 

}