Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generate array with foreach PDO / MySQL

I am doing a select from MySQL that brings me different number of rows for the same column, so I am using foreach to create an array and next I ill merge with another array to finaly echo using json encode, the problem is simple for you… I need to remove the extra array and the keys
when generate the array, I tried with different codes but didn’t worked, could you tell me what I am doing wrong?

Here’s my code:

    $dados2 = [
        'id' => $_POST['id_profissional']
    ];

    $sql2 = "
    SELECT nome
    FROM areas_de_atuacao_dos_advogados_e_escritorios 
    LEFT JOIN areas_de_atuacao ON areas_de_atuacao_dos_advogados_e_escritorios.id_areas_de_atuacao = areas_de_atuacao.id
    WHERE id_advogados_e_escritorios=:id
    ORDER BY principal DESC 
    ";

    $stmt2 = $pdo->prepare($sql2);
    $stmt2->execute($dados2);
    $areas_de_atuacao = $stmt2->fetchAll();


    $i = '0';
    foreach ($areas_de_atuacao as $row) {

        $aAreas_de_atuacao [] = array(
            'area_de_atuacao_'.$i   =>  $row["nome"]
        );
        $i++;

    }

With this output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Array ( [0] => Array ( [area_de_atuacao_0] => Direito Civil ) [1] => Array ( [area_de_atuacao_1] => Direito Criminal ) [2] => Array ( [area_de_atuacao_2] => Direito Empresarial ) [3] => Array ( [area_de_atuacao_3] => Direito de Família ) [4] => Array ( [area_de_atuacao_4] => Direito das Sucessões ) [5] => Array ( [area_de_atuacao_5] => Direito do Trabalho ) )

But this is my desire output:

Array ( [area_de_atuacao_0] => Direito Civil [area_de_atuacao_1] => Direito Criminal [area_de_atuacao_2] => Direito Empresarial [area_de_atuacao_3] => Direito de Família [area_de_atuacao_4] => Direito das Sucessões [area_de_atuacao_5] => Direito do Trabalho )

Thank you for your time 😉

>Solution :

foreach ($areas_de_atuacao as $i => $row) {
    $aAreas_de_atuacao ['area_de_atuacao_'.$i] = $row["nome"];
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading