More or less a Select in array

Asked

Viewed 95 times

1

Good evening, I have two Arrays:

$array1 = ( 

[0] => Array ("Nome":"Rodrigo","CPF":"123456789-00","Cargo":"Abestado")
[1] => Array ("Nome":"Maria","CPF":"987654321-00","Cargo":"Abestada")

$array2 = ( 

[0] => Array ("CPF":"123456789-00","Titulo de Eleitor":"456789123")
[1] => Array ("CPF":"987654321-00","Titulo de Eleitor":"987564123")

In these arrays I have many records. What I want to know is if you can do a CPF query between the arrays. So I look for CPF from $array1 = CPF from $array2. When the result is TRUE, I want the data that differs between arrays to be embedded in $array3 like this:

$array3 = ( 

[0] => Array ("Nome":"Rodrigo","CPF":"123456789-00","Cargo":"Abestado","Titulo de Eleitor":"987564123")
[1] => Array ("Nome":"Maria","CPF":"987654321-00","Cargo":"Abestada","Titulo de Eleitor":"987564123")

That’s possible?

Thanks for your help

3 answers

2


Another way that most values performance is:

  • Create an auxiliary array based on array2 use the cpf as key for the research to be done in Central time, O(1).
  • Traverse each element of array1 and if you find the cpf in the array2 adds the merging of the two arrays to the final array via the function array_merge

Implementation:

$arrayChaves = Array(); //array com cpfs como chaves
foreach($array2 as $valor){
    $chave = $valor["CPF"];
    $arrayChaves[$chave] = $valor;
    unset($arrayChaves[$chave]["CPF"]); //retirar cpf dos valores parar ficar só como chave
}

$arrayFinal = Array();
foreach($array1 as $pessoa){
    $cpfPessoa = $pessoa["CPF"];
    if (isset($arrayChaves[$cpfPessoa])){ //se o cpf existe no arrayChaves
        //adiciona a junção dos dois arrays
        $arrayFinal[] = array_merge($pessoa, $arrayChaves[$cpfPessoa]);
    }
}

See this example working on Ideone

In this example the result was built in another array I called $arrayFinal. You can also change the $array1 which has directly, rewriting a little last for:

foreach($array1 as $pos => $pessoa){ //agora com chave e valor
    $cpfPessoa = $pessoa["CPF"];
    if (isset($arrayChaves[$cpfPessoa])){ //se o cpf existe no arrayChaves
        //a modificação é feita pelo array1 e a sua chave
        $array1[$pos] = array_merge($pessoa, $arrayChaves[$cpfPessoa]);
    }
}

See also this example in Ideone

  • Great answer to you! I improved the performance of my code thanks to your answer. =)

  • 1

    @Andreicoelho Good :). In fact now it was much better, saving previously the transformation in columns not to have to do at each step.

  • Perfect Isac! Exactly that!

  • Simply Perfect man. Thank you Isac

  • 1

    Andrei, only unfortunately you can not check the two answers. Because it is clear that the Isac response was an improvement of yours. Thank you for your time.

  • @Rodrigopereiradefreitas tranquil! I also found the answer of Isac better. =)

Show 1 more comment

1

You can use the array_column to take all the values of an array of a specific key together with the array_search to find out if the searched value exists. And then insert into the new array:

    $array1 =   array( 
        array ("Nome" => "Rodrigo","CPF" => "123456789-00","Cargo"=>"Abestado"),
        array("Nome" => "Andrei","CPF" => "12312313-00","Cargo"=>"Abestado em Programação")
    );
    $array2 =array(array ("CPF"=>"123456789-00","Titulo de Eleitor"=>"456789123")) ;

    $array3 = array();

    $colunas = array_column($array2, 'CPF');

    foreach($array1 as $pessoas){
        if(($key = array_search($pessoas['CPF'],$colunas)) !== false)
            $array3[] = array(
                "Nome" => $pessoas['Nome'], 
                "CPF" => $pessoas['CPF'], 
                "Cargo" => $pessoas['Cargo'],
                "Titulo de Eleitor" =>  $array2[$key]['Titulo de Eleitor']
            );

    }

    print_r($array3);

Exit will be:

Array ( [0] => Array ( [Name] => Rodrigo [CPF] => 123456789-00 [Job] => Statesman [Voter Registration] => 456789123 ) )

0

Edited:

No-frills:

$array3 = array_replace_recursive($array1,$array2);
  • John, good night. I haven’t tested your code, so I’m sorry. I used the Isac response that really boosted code performance. was very fast and the result was above expected. I will study your code because it seemed very good too ok. hug

Browser other questions tagged

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