sql >> Database >  >> RDS >> Mysql

PHP SQL Join Query inhoud samenvoegen in Multi-Array

Je zou dit kunnen doen met een combinatie van PHP en MySQL. Verander uw zoekopdracht in dit:

SELECT section_titel as t1, GROUP_CONCAT(sub_section_titel) as t2 
FROM sections LEFT JOIN sub_sections ON section_id = sId
GROUP BY t1
HAVING t2 IS NOT NULL

Dit geeft je een resultatentabel zoals deze:

t1              t2
Section One     SubOne,SubTwo
Section Three   SubThree

(Als u een resultaat wilt voor Section Two , verwijder de HAVING t2 IS NOT NULL voorwaarde uit de zoekopdracht)

Dan in je PHP (ik neem aan mysqli met een verbinding $conn )

$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
$out = array();
while ($row = mysqli_fetch_array($result)) {
   $out[] = array('t1' => $row['t1'], 't2' => explode(',', $row['t2']));
}
print_r($out);

Uitgang:

Array
(
    [0] => Array
        (
            [t1] => Section One
            [t2] => Array
                (
                    [0] => SubOne
                    [1] => SubTwo
                )    
        )

    [1] => Array
        (
            [t1] => Section Three
            [t2] => Array
                (
                    [0] => SubThree
                )
        )
)


  1. Tijdzones gebruiken in een PHP-webtoepassing

  2. SQL LIKE % binnen array

  3. Toegang tot resultatensets vanuit opgeslagen procedures Transact-SQL SQL Server

  4. Salesforce bijwerken vanuit Oracle®