2014-06-11 83 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; 
     } 
    } 

}