Reputation: 1168
I'm trying to write a PHP function to loop into a multidimensional array to match it with a business name then return to me the "business type".
With my current skills, I wrote this function but I would like to know if there's a better solution other than looping twice because my real arrays are much bigger than the example below.
Note: I'm a student, I already searched StackOverflow but couldn't find my need.
function find_business_type($dealer_name) {
$business_type = [
"OEM" => ["kia", "mercedes"],
"Rent" => ["rent", "rent-a-car"],
"Workshop" => ["shop", "workshop"],
"Spare Parts" => ["spare", "parts", "part"],
"General Trading" => ["gen", "general"]
];
foreach ($business_type as $key => $values) {
foreach ($values as $value) {
if (strpos($dealer_name, $value) !== false) {
return $key;
}
}
}
}
$my_dealer = "super-stars-123 rent a car";
echo find_business_type($my_dealer);
Output: "Rent"
Upvotes: 4
Views: 266
Reputation: 1916
Here's an idea. Essentially, you can filter the array and grab all the rows that match your string based on a percent. Note that array_filter will return an array with all the matching values not just one match.
<?php
$dealer = "super-stars-123 rent a car";
$types = [
"OEM" => ["kia", "mercedes"],
"Stars" => ["super-stars", "123"],
"Brown" => ["super stars", "abc"],
"Home" => ["think rent", "123"],
"Super" => ["renter", "car"],
"Rent" => ["rent", "rent-a-car"],
"Workshop" => ["shop", "workshop"],
"Spare Parts" => ["spare", "parts", "part"],
"General Trading" => ["gen", "general"]
];
// Filter through your array
$results = array_filter($types, function($type) use ($dealer) {
// explode your inner array to a string and then try to match it
// to your search dealer text. This returns a % match.
// I would play around with this algo logic below to get it to do what you want.
return (similar_text($dealer, implode(", ",$type), $percent) >= 8);
});
var_dump($results);
array (size=4)
'Stars' =>
array (size=2)
0 => string 'super-stars' (length=11)
1 => string '123' (length=3)
'Brown' =>
array (size=2)
0 => string 'super stars' (length=11)
1 => string 'abc' (length=3)
'Super' =>
array (size=2)
0 => string 'renter' (length=6)
1 => string 'car' (length=3)
'Rent' =>
array (size=2)
0 => string 'rent' (length=4)
1 => string 'rent-a-car' (length=10)
Upvotes: 3