nitiphone2021 Posted May 5, 2021 Share Posted May 5, 2021 Dear All, As I would like to create json as below format { "data": [ { "title": "After getting a COVID-19 Vaccine", "content": [ { "list": "You may have some side effects, which are normal signs that your body is building protection." }, { "list": "Following symptoms can take place, and it usually resolves within 2 to 3 days." }, { "list": "Common Side Effects pain, redness, swelling, warmth, nausea, muscle pain, tiredness, headache" } ] }, { "title": "After getting a COVID-19 Vaccine", "content": [ { "list": "You may have some side effects, which are normal signs that your body is building protection." }, { "list": "Following symptoms can take place, and it usually resolves within 2 to 3 days." }, { "list": "Common Side Effects pain, redness, swelling, warmth, nausea, muscle pain, tiredness, headache" } ] } ] } The information is from mysql select command: SELECT (tb_helpinfo.title_eng) as title,(tb_helpdetail.content_eng) as content FROM tb_helpinfo INNER JOIN tb_helpdetail ON tb_helpinfo.id = tb_helpdetail.helpinfo_id How could I make json like that from mysql information? Quote Link to comment https://forums.phpfreaks.com/topic/312608-php-create-json-from-inner-join-table/ Share on other sites More sharing options...
gw1500se Posted May 5, 2021 Share Posted May 5, 2021 Use json_encode. Quote Link to comment https://forums.phpfreaks.com/topic/312608-php-create-json-from-inner-join-table/#findComment-1586329 Share on other sites More sharing options...
nitiphone2021 Posted May 5, 2021 Author Share Posted May 5, 2021 12 minutes ago, gw1500se said: Use json_encode. Yes, but how we create the query to be the json format like my target? Quote Link to comment https://forums.phpfreaks.com/topic/312608-php-create-json-from-inner-join-table/#findComment-1586330 Share on other sites More sharing options...
Barand Posted May 5, 2021 Share Posted May 5, 2021 Depends the structure you want for your array. Using your existing query... $res = $pdo->query("SELECT i.title_eng as title , d.content_eng as content FROM tb_helpinfo i INNER JOIN tb_helpdetail d ON i.id = d.helpinfo_id ORDER BY title "); ## METHOD 1 $data = []; foreach ($res as $r) { if (!isset($data[$r['title']])) { $data[$r['title']] = []; } $data[$r['title']][] = $r['content']; } echo '<pre> Method 1 ', print_r($data, 1), '</pre>'; echo json_encode($data); ## METHOD 2 $data = $res->fetchAll(); echo '<pre> Method 2 ', print_r($data, 1), '</pre>'; echo json_encode($data); Quote Link to comment https://forums.phpfreaks.com/topic/312608-php-create-json-from-inner-join-table/#findComment-1586331 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.