PHP数组和基于文本的数组映射


php arrays and array mapping based on text

根据发货方法得到不同的订单文本字符串。例如,订单可以返回以下任何内容:

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';

做这件事的最好方法是什么?

您可以使用foreach和stripos来匹配场景。

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;
        }
    }
}

好了,这里有一个名为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