0

I have 3 different multidimensional arrays:

// INPUT DATA WITH HOUSE DESCRIPTION. STRUCTURE: ID, OPTION DESCRIPTION

$input_house_data = array (
array("AAA","Chimney with red bricks"),
array("BBB","Two wide windows in the main floor"),
array("CCC","Roof tiles renewed in 2015")
);

// CATALOGUE WITH ALL HOUSE EQUIPMENT OPTIONS. STRUCTURE: ID, OPTION NAME

$ct_all_house_options = array (
  array("0001","Chimney"),
  array("0002","Garden"),
  array("0003","Roof tiles"),
  array("0004","Windows"),
  array("0005","Garage")
);

// SEARCH STRINGS AS REGULAR EXPRESSIONS. STRUCTURE: ID, EQUIPMENT OPTION NAME, REGULAR EXPRESSION TO SEARCH

$ct_house_options = array (
  array("0001","Chimney","/^Chimney with./"),
  array("0003","Roof tiles","/^Roof tiles./"),
  array("0004","Windows","/.windows./"),
  array("0004","Windows","/.wide windows./")    
);

I would like to search within $input_house_data by use of the regular expressions from the array $ct_house_options in order to indicate which equipment has a house. The result should be the whole list with all possible options and status "available" or "not available":

0001 - Chimney - available
0002 - Garden - not available
0003 - Roof tiles - available
0004 - Windows - available
0005 - Garage - not available

I tried to realize it as following:

$arrlength_input_house_data = count($input_house_data);
$arrlength_ct_all_house_options = count($ct_all_house_options);
$arrlength_ct_house_options = count($ct_house_options);

For loop with preg_match function. All results are written into array $matches (including dublicates):

for ($row1 = 0; $row1 < $arrlength_input_house_data; $row1++) {

   for ($row2 = 0; $row2 < $arrlength_ct_house_options; $row2++) {
   
if (preg_match($ct_house_options[$row2][2], $input_house_data[$row1][1]) === 1) {
    $matches[] = $ct_house_options [$row2][0];
}
}
}

Deleting of duplicates:

$unique = array_unique($matches);
print_r($unique);

So now I have got the unique results:

Array ( [0] => 0001 [1] => 0004 [3] => 0003 )

The next step should be merge of the array $ct_all_house_options and unique results from $unique. Unfortunately, I cannot get it realized. Do you have any idea how to get it? Maybe there is a more simple way to realize it?

12.08.2022

Hello dear all! thank you for your feedbacks. I checked and tested all of of them. Inbetween the business logic has been changed and became a little bit complicated:

1.There are 3 different constelations to indicate a product option.

  • Only by regular expression within product description,
  • By regular expression within description + product family or parts of product family,
  • By regular expression within description + product family + product number.

2.The output can be different: TRUE/FALSE or specific string (e. g. color of the product "white", "green" etc.).

So please take a look how I designed a possible solution:


$input_product_data = array (
array("AAAA", "9999", "Chimney with red bricks"),
array("CCCC","2234","Two wide windows in the main floor"),
array("RRRR","0022","Roof tiles renewed in 2015"),
array("","2258","Floor has been renovated for two years. Currently it has ground in wood."),
array("","","Beautiful door in green color")

);

// CUSTOMIZING TABLE FOR PRODUCT OPTIONS. STRUCTURE: ID[0], OPTION NAME[1], OPTION CATEGORY[2], OPTION-FAMILY[3], PROD.-NR[4], REG. EXPRESSION[5], PRIORITY[6], OUTPUT[7]

$ct_product_options = array (
  array("0001", "Chimney", "Additional options", "/^AAAA/", "9999", "/^Chimney with./", "0", "TRUE"),
  array("0003", "Roof tiles", "Basic options", "/^RRRR/", "0022", "/^Roof tiles./", "0", "TRUE"),
  array("0004", "Windows", "Basic options", "/^C...$/", "2234", "/.windows./", "0", "TRUE"),
  array("0004", "Windows", "Basic options", "/^C...$/", "2567", "/.wide windows./", "0", "TRUE"), 
  array("0002", "Material of ground floor", "Additional options", "", "/^2.../", "/.wood./", "0", "Wood"),  
  array("0005", "Door color", "Basic options", "", "", "/.green./", "0", "Green") 
  
);

// IMPORTANT: THE REG. EXPRESSIONS CAN BE DEFINED MANY TIMES (e. g. 10 DIFFERENT REG. EXPRESSIONS FOR OPTION "WINDOWS"). POINTS "." REPRESENTS EMPTY SPACES WITHIN PRODUCT DESCRIPTION AND ARE IMPORTANT TO IDENTIFY EXACTLY AN OPTION. 


// FOR LOOP TO MAKE COMPARISON BETWEEN INPUT PRODUCT DATA AND PREDEFINED CUST. STRINGS

$matches_array = array();

foreach ($input_product_data as [$product_family, $product_number, $product_description]) {
    foreach($ct_product_options as [$option_id, $option_name, $option_category, $product_family_reg_exp, $product_number_reg_exp, $regular_expression, $priority, $output]) {
        
   if (preg_match($regular_expression, $product_description) == 1
   &&  preg_match($product_family_reg_exp, $product_family) == 1 ||
   
       preg_match($regular_expression, $product_description) == 1
   &&  preg_match($product_number_reg_exp, $product_number) == 1) {
    
    $matches_array [] = array("id" => $option_id, "option_name" => $option_name, "option_category" => $option_category, "output"=> $output);
    
    
    } 
    
    else {

   if (empty($product_family) && empty($product_number)) {

   if (preg_match($regular_expression, $product_description) == 1) {
    
    $matches_array [] = array("id" => $option_id, "option_name" => $option_name, "option_category" => $option_category, "output"=> $output);
    
   }
   }
    }   
  }
}

echo "<pre>";
print_r($matches_array);

// FUNCTION FOR DELETE DUBLICATES FROM ARRAY WITH MATCHES

function unique_multidimensional_array($array, $key) {
$temp_array = array();
$i = 0;
$key_array = array();

foreach($array as $val) {
    if (!in_array($val[$key], $key_array)) {
        $key_array[$i] = $val[$key];
        $temp_array[$i] = $val;
    }
    $i++;
}
return $temp_array;
}

echo "<br><h3>UNIQUE MATCHES</h3>";

// CALL OF THE FUNCTION TO GET UNIQUE MATCHES

$unique_matches = unique_multidimensional_array($matches_array, 'id');
sort($unique_matches);
echo "<pre>";
print_r($unique_matches);

// CALL OF THE FUNCTION TO CREATE LIST/ARRAY WITH ALL AVAILABLE PRODUCT OPTIONS

$list_all_product_options = unique_multidimensional_array($ct_product_options, 0);
$list_all_product_options_short = array();

foreach ($list_all_product_options as $option_item) {
    $list_all_product_options_short[] =  array("option_id" => $option_item[0], "option_name" => $option_item[1], "option_category" => $option_item[2]);
}

sort($list_all_product_options_short);

echo "<h3>LIST WITH ALL PRODUCT OPTIONS (SHORT VERSION)</h3>";
echo "<pre>";
print_r($list_all_product_options_short);

My questions:

1.How to get crossed two arrays $list_all_product_options_short and $unique_matches within an array in the following format: ALL values from $list_all_product_options_short and only field "output" from $unique_matches?

// EXAMPLE:

0001 - Chimney - Additional options - TRUE
0005 - Door color - Basic options - Green

// etc.

2.Additionally within indication process should be considered new parameter "Priority". It should be used to rewrite/to prioritise results for certain cases. E.g. when we have got two different colors for door "green" (priority = "0") and "red" (priority ="1"), door should get "Output" = "red".

3.For some hints regarding better coding for better performance I would be very appreciate.

3
  • You should learn to use foreach instead of for when looping over arrays,
    – Barmar
    Aug 5, 2022 at 20:22
  • You'll need to clarify what kind of output you're looking for, it's not clear from your question what your end goal is here.
    – miken32
    Aug 5, 2022 at 20:26
  • 1
    I think it only damages this page to substantially deviate the question svope/details after receiving answers. I recommend rolling the question back to an earlier version and asking a new, clear question. Aug 13, 2022 at 19:14

3 Answers 3

0

Loop through the array with all options. Check if the ID is in your $unique list, then it's available.

foreach ($ct_all_house_options as [$id, $name]) {
    if (in_array($id, $unique)) {
        echo "$id - $name - available<br>";
    } else {
        echo "$id - $name - not available<br>";
    }
}
2
  • Thanks Barmar, it works! )) Is any way to realize it more smarter? I mean less code which will work with better performance? Aug 5, 2022 at 20:39
  • I don't think there's much you can do to improve the nested loops that are matching the regexps.
    – Barmar
    Aug 5, 2022 at 20:54
0

If performance is very important, you can prepare associative arrays to access the data faster. Here's a solution for the entire problem:

$optionsById = [];
foreach ($ct_house_options as $option) {
    $optionsById[$option[0]] = $option;
}

$availabilityById = [];
foreach ($ct_all_house_options as $option) {
    $id = $option[0];
    $availabilityById[$id] = false;
    foreach ($input_house_data as $data) {
        $option = $optionsById[$id] ?? null;
        if (!$option) {
            continue;
        }
        if (preg_match($option[2], $data['1'])) {
            $availabilityById[$id] = true;
            break;
        }
        
    }
}

foreach ($ct_all_house_options as $option) {
    $availabilityString = $availabilityById[$option[0]]
        ? 'available'
        : 'not available';
    echo "$option[0] - $option[1] - $availabilityString\n";
}

Performance:

  • Execution time:
    • min: 0.00000476837158203s
    • max: 0.00047588348388672s
    • avg: 0.0000226473808289s
  • Memory usage: 396KB

It's possible to do it with less code, though, if the foreach loop is changed:

$available = [];
foreach ($input_house_data as $data) {
    foreach ($ct_house_options as $option) {
        if (preg_match($option[2], $data['1'])) {
            $available[$option[0]] = true;
        }   
    }
}

foreach($ct_all_house_options as $option) {
    $availabilityString = isset($available)
        ? 'available'
        : 'not available';
    echo "$option[0] - $option[1] - $availabilityString\n";
}

Performance:

  • Execution time:
    • min: 0.00000691413879395s
    • max: 0.00018811225891113s
    • avg: 0.0000229740142822s
  • Memory usage: 396KB

If you still want to use the $unique, you can still prepare an associative array for performance reasons:

$indexById = array_flip($unique);
foreach ($ct_all_house_options as $option) {
    $availabilityString = isset($indexById[$option[0]])
        ? 'available'
        : 'not available';
    echo "$option[0] - $option[1] - $availabilityString\n";
}

Performance:

  • Execution time:
    • min: 0.00000905990600586s
    • max: 0.00018906593322754s
    • avg: 0.0000392961502075s
  • Memory usage: 397KB

Using in_array instead:

foreach ($ct_all_house_options as $option) {
    $availabilityString = in_array($option[0], $unique)
        ? 'available'
        : 'not available';
    echo "$option[0] - $option[1] - $availabilityString\n";
}
  • Execution time:

    • min: 0.0000100135803223s
    • max: 0.0050561428070068s
    • avg: 0.0000860285758972s
  • Memory usage: 396KB

I used PHP Sandbox to perform the tests. Of course, the execution time is not always the same.

3
  • Thank you for your feedbacks. I checked and tested all of of them. In between the business logic has been changed and became complicated. Please see my update from 12.08.2022 and my approach above. Aug 12, 2022 at 10:49
  • I believe you should submit a new question. Otherwise, you won't get answers and you might be flagged for changing the scope. I think my second suggestion is the simplest, easier to change, and very efficient. Doing all those foreach, if, etc. make the code harder to understand and change. I might help if I find another submission for the different questions. Aug 14, 2022 at 2:10
  • 1
    Hello, I posted new questions with 2 different solutions here: stackoverflow.com/questions/73420771/… Aug 19, 2022 at 18:16
0
  1. Only column 1 of $input_house_data has value. By imploding the values into a consolidated haystack string, you reduce the total number of preg_match() calls needed.
  2. Every house option should have its own single regex pattern. You could make a separate lookup array, but I would simply add a regex column to the "all options" array.

Code: (Demo) (or with a lookup array)

$dwellingInfo = [
    ["AAA", "Chimney with red bricks"],
    ["BBB", "Two wide windows in the main floor"],
    ["CCC", "Roof tiles renewed in 2015"]
];

$haystack = implode(
    ',',
    array_column($dwellingInfo, 1)
);

$dwellingAttributes = [
    ["0001", 'Chimney', '/\b(?:Chimney with|Big stove)\b/i'],
    ["0002", 'Garden', '/\bgarden\b/i'],
    ["0003", 'Roof tiles', '/\bRoof tiles\b/i'],
    ["0004", 'Windows', '/\bwindows?\b/i'],
    ["0005", 'Garage', '/\b(?:garage|car port|under cover area)\b/i']
];

foreach ($dwellingAttributes as [$id, $term, $pattern]) {
    printf(
        "%s - %s - %s\n",
        $id,
        $term,
        preg_match($pattern, $haystack)
            ? 'available'
            : 'unavailable'
    );
}

Output:

0001 - Chimney - available
0002 - Garden - unavailable
0003 - Roof tiles - available
0004 - Windows - available
0005 - Garage - unavailable
9
  • Hello mickmackusa, thanks for your feedback. The approach is good! But the problem is that it will not work for me because the search strings/reg. expressions in the real case are much complexer as described above. e. g. we need to indicate the eqipment option "Chimney" by use of the reg. expression "/^Big stove./" within description "Big stove with wide door". Aug 6, 2022 at 11:02
  • @Clip I've updated. Aug 6, 2022 at 13:24
  • The overarching advice that I have for you is that you should not be creating multiple regexes for a single attribute. The . in your patterns seems to be misunderstood. If you'd like to have your working technique reviewed more carefully, I recommend posting your script on Code Review. Aug 8, 2022 at 23:18
  • The multiple regex are given by business process. There are hundreds of the search strings and new will be created permanently in the future. Point "." or many points are part of the business logic. They represent empty spaces or certain number of some signs. So, from my point of view is it not possible to consolidate of all them and keep them consistent in the future. Aug 12, 2022 at 10:46
  • Seems like a nightmare to maintain. I would personally devote time to consolidating regexes. The benefits include: improved performance and maintenance. Aug 12, 2022 at 11:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.