Code exécutable avec quelques exemples de données :http://codepad.org/2Xsbdu23
J'ai utilisé 3 SELECT
distincts s pour éviter les répétitions inutiles.Bien sûr il faut personnaliser le $result
tableau au format JSON exact souhaité, mais je pense que ce n'est pas si difficile.
// assume $t1/2/3 will be arrays of objects
$t1 =
SELECT Table1.*
FROM Table1
WHERE Table1.ID = 111
$t2 =
SELECT Table2.*
FROM Table2
WHERE Table2.table1_ID = 111
$t3 =
SELECT Table3.*
FROM Table2
INNER JOIN Table3 ON Table2.ID = Table3.table2_ID
WHERE Table2.table1_ID = 111
function array_group_by( $array, $id ){
$groups = array();
foreach( $array as $row ) $groups[ $row -> $id ][] = $row;
return $groups;
}
// group rows from table2/table3 by their parent IDs
$p2 = array_group_by( $t2, 'table1_ID' );
$p3 = array_group_by( $t3, 'table2_ID' );
// let's combine results:
$result = array();
foreach( $t1 as $row1 ){
$row1 -> Table2_Objects = isset( $p2[ $row1 -> ID ]) ? $p2[ $row1 -> ID ] : array();
foreach( $row1 -> Table2_Objects as $row2 )
$row2 -> Table3_Objects = isset( $p3[ $row2 -> ID ]) ? $p3[ $row2 -> ID ] : array();
$result[] = $row1;
}
echo json_encode( $result );