php - Dump data in json format from two tables from MySQL -
i have following scenario. have 2 tables follow table 1 id, name, desc, seo
table 2 id, table1_id, relation_table1_id
in table 1 have data need as:
----------------------------------- |id | name |desc |seo | ----------------------------------- | 1 | smith |father |f | | 2 | jonh |son |j | | 3 | margat |mother |m | | 4 | bis3 |son |b1 | | 5 | bis2 |son |b2 | | 6 | bis1 |son |b3 | | 7 | lanos |brother |l | -----------------------------------
and have our table 2 follow
------------------------------------- |id | table1_id |relation_table1_id| -------------------------------------- | 1 | 1 | 4 | | 2 | 1 | 5 | | 3 | 3 | 6 | | 4 | 3 | 2 | | 5 | 7 | 0 | --------------------------------------
so far have first table dump json() follow:
<?php include ('config.php'); $dump1 = mysql_query("select * table1 ") or die(mysql_error()); $getlist = array(); while ($row = mysql_fetch_assoc($dump1)) { $getlist[] = $row; } print json_encode($getlist); exit; ?>
that code give me following:
[ { "id":"1", "name":"smith", "desc":"father", "seo":"f" }, { "id":"2", "name":"jonh", "desc":"son", "seo":"j" }, { "id":"3", "name":"margat", "desc":"mother", "seo":"m" }... ... ... ]
what can't figure how following
[ { "id":"1", "name":"smith", "desc":"father", "seo":"f", "relations":[ { "id":"4", "name":"bis3", "desc":"son", "seo":"b1" } ] }, { "id":"3", "name":"margat", "desc":"father", "seo":"f", "relations":[ { "id":"6", "name":"bis2", "desc":"son", "seo":"b2" }, { "id":"2", "name":"jonh", "desc":"son", "seo":"j" } ] }... ... ... ]
in plain text like
id 1 smith | |_id 4 bis3 | |_ id 3 margat |_id 5 bis2 |_id 2 jonh
i'm learning how use json , got first part can see, lack of knowledge of sql , php wont let me want, please can 1 me achieve scenario please.
thank you.
you can loop through $getlist
then query
for($i = 0; $i <= count($getlist); $i++){ "select * table2 table1_id = $getlist[$i]['id']" // result way $getlist[$i]['something'] = $result; }
then take result of that, inside loop, , assign whichever key of getlist want example
hopefully thats specific enough. let me know if have problems that.
Comments
Post a Comment