Recursively relate items from an array to PHP

Asked

Viewed 131 times

3

I wonder if there is any native PHP function to relate all array items to all other array items, example:

$arr['a'] = [1,2,3];
$arr['b'] = [4,5];
$arr['c'] = [7,8,9,10];

To get the following result:

$result[] = [1,4,7];
$result[] = [1,4,8];
$result[] = [1,4,9];
$result[] = [1,4,10];
$result[] = [1,5,7];
$result[] = [1,5,8];

And so on, until all have related, and the initial arrays can vary in number as well as their contents.

1 answer

2


I did not find anything native but I solved this way, it worked for me!

    $arr_ovp = [ 'Cor'      => ['White','Black','Green','Blue','Red'],
                 'Tamanho'  => ['G','XG','XXL','XXG'],
                 'Manga'    => ['Curta','Cumprida','SemManga'],
                 'Estampa'  => ['Breaking Bad','Back to the Future','Star Wars']];



foreach($arr_ovp as $variacoes) {

    if( empty($arr1) ) {
        foreach($variacoes as $variacao) {
            $arr1[] = $variacao;
        }
    } else {
        foreach($arr1 as $opcao) {
            foreach($variacoes as $variacao) {
                $arr2[] = $opcao.' - '.$variacao;
            }
        }
        $arr1 = $arr2;
        $arr2 = '';
    }
}
echo "<pre>";
print_r($arr1);
exit;

  • "Recursively relate array items" - Your solution is not recursive.

  • It’s not really recursive, but it’s solved for me, recurs there and glue here! vlw.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.