Match the Arrays

Asked

Viewed 39 times

-1

Personal how can I combine arrays in the following example array:

$cor = array('branco', 'preto');

I would like the combination of arrays to look like this:

$cor = array('branco', 'brancopreto', 'preto', 'pretobranco');

I tried that

$cor = "Preto Branco";

$cor  = explode(" ",$cor);

$juncao = array_merge($cor, $cor); 


foreach ($juncao as $value) {
  echo $value . "<br>";
}

  • Hi buddy... I tried to use array_merge($arr1, $arr2) more I saw that’s not quite it

  • Quiet I’m gonna do it !

2 answers

0

You can use the array_map and the array_walk method:

$cor = "Preto Branco Azul Amarelo";

$cor  = explode(" ",$cor);

$output = array_map(function($key, $value, $cor){
    global $cor;
    $new_cor = $cor;
    array_walk($new_cor, function(&$value, $key, $value2) {
        //Concatena o valor do array se nao tiver o mesmo valor
        ($value != $value2)?$value = $value2.$value:$value; 
    }, $value);
    
    return $new_cor;
    
}, array_keys($cor), array_values($cor), $cor);

//Merge o seu array para uma so dimensao
print_r(call_user_func_array('array_merge',$output));

-1


Hello! I believe this algorithm solves your problem:

 $cor = "Preto Branco vermelho azul rosa amarelo";

        $cor  = explode(" ",$cor);
        
        $arr = [];
        //verifica se é par
        if(sizeof($cor)%2 == 0) {
            for($i = 0; $i < sizeof($cor); $i++)
            {
                $arr[] = $cor[$i]; //Preto
                $arr[] = $cor[$i] . $cor[$i + 1]; //PretoBranco
                $arr[] = $cor[$i + 1]; //Branco
                $arr[] = $cor[$i + 1] . $cor[$i]; // $BrancoPreto
                $i++; //pula indice impar
            }
            foreach ($arr as $value) {
                echo $value . "<br>";
              }
        } else {
            echo "numero de cor impar, impossivel combinação";
        }

Accepts even array only for combinations.

  • Perfect worked out !

Browser other questions tagged

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