PHP: combine arrays using strpos and str_replace

Viewed 38

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.

2 Answers

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 use foreach instead of for.

foreach ($alertTypes as $alert) {
    $array = [];
    foreach ($channels as $channel) {
        if (strpos($channel, $alert) !== false) {
            $array[] = str_replace($alert, '', $channel);
        }
    }
    $result[$alert] = $array;
}

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

?>
Related