Working with PHP arrays and mapping them based on textual data

When processing orders, different text strings are returned based on the shipping method selected. Examples of these text strings include:

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

In order to map these text strings to production codes, a key-value pair map is used. The key represents the text to match on and the value indicates the corresponding production code. The mapping table looks like this:

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

The objective is to create a function that can return the correct production code from the $shipToProductionMap based on the input string provided. This function could look something like:

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

For instance, if the function call is as follows:

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

What would be the most efficient approach to achieve this?

Answer №1

To accomplish this task, you can utilize the foreach loop along with the stripos function for matching purposes.

echo getShipCode('productmatrix_2-Day_Delivery');

function getShipCode($text){

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

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

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

            return $value;

            break;
        }
    }

}

Answer №2

Here is a function called getCorrectShipCode that compares array key values in the ship to production map against a string passed to it using preg_match. This function works by iterating through all values in a test array:

// Populate the test array with strings.
$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';

// Iterate through test array strings.
foreach ($test_strings as $test_string) {
  echo getCorrectShipCode($test_string) . '<br />';
}

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

  // Define 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 ship to production map keys.
  $regex_pattern = '/(?:' . implode('|', array_keys($shipToProductionMap)) . ')/i';

  // Use regex to match the value based on the ship to production map keys.
  preg_match($regex_pattern, $text, $matches);

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

} // getCorrectShipCode

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Efficiently transforming an OpenMaya MPoint array into an imath V3f array in Python

I am faced with the challenge of connecting two APIs that have different data format requirements and I am looking for a quick solution to convert large arrays of one type into the other using Python instead of C++. One API (Maya) provides points in the f ...

Issue with Laravel Composer: Failed to install, restoring original content in ./composer.json

I am fairly new to Laravel and I have been using Laravel 5.8 for my project development. Recently, I needed to access the file ExampleComponent.vue in the resources/js/components directory but it was not there. After referencing this link, I came to know ...

What is the best way to display the values of a multi-dimensional array in Smarty?

In my smarty template, I am trying to display the content of an array called $all_class_subjects: Array ( [4] => Array ( [class_id] => 5 [class_name] => V [class_order] => 0 [class_subjec ...

PHP code malfunctioning within an HTML document

After setting up XAMPP and getting Apache to run successfully, I created a file named helloworld.php in the htdocs folder. However, I encountered an issue where my PHP script within an HTML file was not displaying in the browser. Since I am new to PHP an ...

What are the steps to enable pagination for get_posts() function in WordPress?

I am currently developing a WordPress website and have designed a page template that showcases posts based on a specific category slug. In order to achieve this, I created a custom field for the page called WP_Catid and assigned it the value of the desired ...

Is there a way for me to automatically go back to the home page when I press the back button on the browser?

My ecommerce website has a shopping cart page where customers can purchase products and make payments. After the payment is completed, they are directed to a thank you page. The flow of the website is as follows: Home page => Products => Shopping cart => ...

What is the reason behind only the initial click boosting the vote count while subsequent clicks do not have the same

In this snippet of code: //JS part echo "<script> function increasevotes(e,location,user,date,vote) { e.preventDefault(); var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState ...

Setting up a Laravel project on a DSO handler server

I am currently working on a Laravel 5.0 project that needs to be tested on servers supporting different PHP handlers such as: 1. suPHP (Single user PHP) 2. FCGI (FastCGI) 3. CGI (Common Gateway Interface) 4. DSO (Dynamic Shared Object) The project ru ...

Using Laravel 5.1 to Redirect and Pass Get Parameters

I am currently troubleshooting a redirect issue in Laravel 5.1 that is leading to the following error NotFoundHttpException in RouteCollection.php line 161: The specific redirect I am attempting to accomplish is as follows: http://example.com/tool/view. ...

What is the best approach to merging multiple arrays to create a new array in CodeIgniter?

Here are two arrays provided below, where I want to combine the first key of the first array with the second key of the second array to create a new array. [animals1] => Array ( [0] => Horse [1] => Dog1 ...

Is it possible for a cronjob to run continuously for a span of 30 minutes?

Recently, I developed a PHP script that generates cache files from an API. Unfortunately, the process takes about 30 minutes to complete loading all the necessary files for the page. I reached out to my hostinger's customer support team who advised m ...

When the page is refreshed, the POST array does not become empty

I recently developed a PHP form with the action set to the same page URL and method as POST. <?php if(isset($_POST['submitted']) && $_POST['submitted'] != ''){ echo $_POST[&apo ...

What lies ahead for the dl() function in the PHP programming language?

After coming across information in the PHP documentation stating that the dl function will be deprecated, I am curious if that means we should discontinue using the dl function in our scripts. If so, is there an alternative method for loading .so files fr ...

Live search with AJAX, navigate to a different page, and showcase the findings

I currently have multiple web pages that all feature the same search form. What I want to achieve is for the results page to load dynamically as the user starts typing, replacing the current page and displaying all relevant items found. How can I implement ...

Error: The JSON array could not be parsed because the value was not found within it

After arranging the array in ascending order, I have obtained the following JSON array: [{"id":0,"dependency":"no","position":0,"type":"textinput","label":"t01"},{"id":0,"dependency":"no","position":1,"type":"textarea","label":"t02"},{"id":1,"dependency": ...

Modifying image size by adjusting width before sending it through a header in php

So, I have this little snippet of code that does some magic with random images and redirects them to another page. The twist is I'm trying to make it handle image widths that exceed a certain maximum width. I made some progress but then hit a roadbloc ...

Is there a way to display the directory link using PHP?

I have a Word document saved in my folder, and its name is already in the database. I want to display this document from the folder using PHP. When someone clicks on the link, the entire document should appear on the front end. $sql = "SELECT * FROM user ...

Determine the percentage using jQuery by considering various factors

I am facing an issue with the following code snippet: <script type="application/javascript"> $(document).ready(function () { $("#market_value").on("change paste keyup", function() { var market_value = par ...

What is the method for verifying a string in the following pattern: +xxx-yyyy-zzzz?

Let's say X, y, and z are all numerical values. Other than being able to verify if a string is exactly 14 characters long, I would prefer not to loop through each character to validate if it falls within the range of [0-9]. Are there more efficient m ...

Encountering an issue when attempting to access a string offset while creating a JSON object in PHP

After countless attempts and failed solutions, I find myself struggling to make this work. The scenario is as follows: I have an initially empty file named contact.json. If the file is empty, I need to add JSON data to it. If it already contains data, I ...