PHP: combine arrays using strpos and str_replace
Get the solution ↓↓↓I have 2 arrays, that look like this:
$alertTypes = ['outbid', 'subAllVendorComments'];
$channels = ['outbiduseSms', 'outbiduseBrowser', 'subAllVendorCommentsuseEmail', 'subAllVendorCommentsuseWhatsApp'];
My aim is to combine them into one array that is structured like this:
Array
(
[outbid] => Array
(
[0] => useSms,
[1] => useBrowser
)
[subAllVendorComments] => Array
(
[0] => useEmail,
[1] => useWhatsApp
)
)
The elements in each sub-array are the words in the $channels array that begin with the word in the $alertTypes array.
I have tried the following, but it doesn't work as it relies on there only being one element in the $channels array that begins with the same word in the $alertTypes array:
$result = [];
for($i = 0; $i < count($alertTypes); $i++) {
if(strpos($channels[$i], $alertTypes[$i]) !== false) {
$result[$alertTypes[$i]] = [str_replace($alertTypes[$i], '', $channels[$i])];
}
}
Any help is appreciated.
Answer
Solution:
You're using the same index$i
for both arrays, which will only work when the string in$alertTypes
is in the corresponding element of$channels
. You need to compare the alert types with all channels, which can be done using nested loops.
You're also replacing the element of$result
instead of pushing onto the nested array.
The code will also be easier if you useforeach
instead offor
.
foreach ($alertTypes as $alert) {
$array = [];
foreach ($channels as $channel) {
if (strpos($channel, $alert) !== false) {
$array[] = str_replace($alert, '', $channel);
}
}
$result[$alert] = $array;
}
Answer
Solution:
Another way to get the same result:
First I set arrayResult with keys from alertTypes's values and empty arrays as values. Then I "walk" array channels, for each channel I check arrayResult keys, and when I found that an arrayResult key is the begging of a channels value, I set it as value of that key in arrayResult.
<?php
$arrayResult = array_combine($alertTypes, array_fill(0, count($alertTypes), array()));
array_walk($channels, function($channel) use (&$arrayResult) {
foreach($arrayResult as $key => $array) {
if(strpos($channel, $key) === 0) {
$arrayResult[$key][] = str_replace($key, '', $channel);
}
}
});
?>
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: filter_sanitize_string deprecated
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.