maune Posted January 25, 2012 Share Posted January 25, 2012 Hello all. I'm pretty new to this, but I'm trying to build a script that will write random questions for a quiz app that I'm working on. The data is contained in two different tables. I'm trying to randomize the question order that is spit out, as well as randomize the answer order that is displayed. The output has to be in the specific JSON string that is denoted in the code. There are no errors when I go the url that I load the script, however, the string is not populated with any of the data from my tables (it is just an empty set of strings in the JSON format that the program requires. Could someone please take a look at this and tell me where I'm going wrong. I've checked that the query is pulling from the correct databases so I know that's not the problem. Thank you in advance. <?php //Connect To Database $hostname=""; $username=""; $password=""; $dbname=""; $question_table="wp_mtouchquiz_question"; $answer_table="wp_mtouchquiz_answer"; $yourfield = "question"; $question = "question"; $answer = "answer"; $connection = mysql_connect($hostname, $username, $password); $lastQuestionID = -1; $str = ""; mysql_select_db($dbname, $connection); # Check If Record Exists $query = "SELECT * FROM $question_table q, $answer_table a WHERE q.ID = a.QUESTION_ID AND q.quiz_id = 1 ORDER BY question_id ASC, correct DESC"; $result = mysql_query($query); $questions = array(); $fields = array(); if($result) { while($row = mysql_fetch_array($result)) { if($lastQuestionID != $row["question_id"]) { $fields = array(); if($lastQuestionID != -1) { array_push($questions, $fields); } $fields = array(); $lastQuestionID = $row["question_id"]; $fields["question_id"] = $row["question_id"]; $fields["question"] = $row["question"]; } // correct if($row["correct"] == 1) { $fields["correct"] = $row["answer"]; } // incorrect if ($row["sort_order"] ==2) { $fields["incorrect0"] = $row["answer"]; } // incorrect if ($row["sort_order"] ==3) { $fields["incorrect1"] = $row["answer"]; } // incorrect if ($row["sort_order"] ==4) { $fields["incorrect2"] = $row["answer"]; } if ($row["sort_order"] ==5) { $fields["incorrect3"] = $row["answer"]; } } $str .= "{\"childItems\":["; $numQuestionsToUse = 172; //Set this larger than returned questions or less than row limit / 5 $randomQuestionKeys = array_rand($questions, $numQuestionsToUse); $numQuestions = count($randomQuestionKeys); for($i = 0; $i < $numQuestions ; $i++){ $pickedField = $questions[$randomQuestionKeys[$i]]; $str .= "{\"itemId\":\"question" . $pickedField["question_id"] . "\","; $str .= "\"itemType\":\"BT_questionItem\","; $str .= "\"questionText\":\"" . $pickedField["question"] . "\","; $str .= "\"correctAnswerText\":\"" . $pickedField["answer"] . "\","; $incorrectAnswers = array(); array_push($incorrectAnswers, $pickedField["incorrect0"]); array_push($incorrectAnswers, $pickedField["incorrect1"]); array_push($incorrectAnswers, $pickedField["incorrect2"]); array_push($incorrectAnswers, $pickedField["incorrect3"]); $incorrectAnsKey = array_rand($incorrectAnswers, 3); $str .= "\"incorrectText1\":\"" . $incorrectAnswers[$incorrectAnsKey[0]] . "\","; $str .= "\"incorrectText2\":\"" . $incorrectAnswers[$incorrectAnsKey[0]] . "\","; $str .= "\"incorrectText3\":\"" . $incorrectAnswers[$incorrectAnsKey[0]] . "\","; $str .= "\"imageURLSmallDevice\":\"http://www.myquizcoach.com/extras/images/clear_header.png\","; $str .= "\"imageURLLargeDevice\":\"http://www.myquizcoach.com/extras/images/clear_header.png\"},"; } // remove last comma $str = substr($str,'',-1); $str .= "] }"; echo $str; } ?> Quote Link to comment Share on other sites More sharing options...
Psycho Posted January 25, 2012 Share Posted January 25, 2012 Start by forgetting about the JSON requirements. First build your script such that you know you have the right data THEN format the data accordingly. I see a lot of things in that code that could be improved/corrected. here are a few: - You have no error handling for the DB operations. Your query could be failing for all you know. - The query is ordering results based upon the correct question - why? For the purposes of generating the test you don't need to know which one is correct or not. That takes place when the answers are submitted. - Don't use '*' in your select statement, only query the fields you need. There is a pretty simple solution. Just populate the data into an array, then use shuffle() to randomize the questions/answers. Here is an example: //Connect To Database $hostname=""; $username=""; $password=""; $dbname=""; $connection = mysql_connect($hostname, $username, $password); if(!$connection) { die('Unable to connect to database server.'); } if(!mysql_select_db($dbname, $connection)) { die('Unable to select database.'); } //Query for questions/answers $question_table="wp_mtouchquiz_question"; $answer_table="wp_mtouchquiz_answer"; $query = "SELECT q.question_id, q.question, a.answer FROM {$question_table} q, JOIN {$answer_table} a ON q.ID = a.QUESTION_ID WHERE q.quiz_id = 1 ORDER BY question_id ASC, correct DESC"; $result = mysql_query($query) or die('Unable to get questions.'); //Populate results into multi-dimensional array $questions = array(); while($row = mysql_fetch_assay($result)) { if(!isset($questions[$row['question_id']])) { $questions[$row['question_id']] = array( 'question' => $row['question'], 'question_id' => $row['question_id'], 'answers' => array() ); } $questions[$row['question_id']]['answers'][] = $row['answer']; } //Randomize the questions and answers shuffle($questions); foreach($questions as &$question) { shuffle($question['answers']); } //NOW output the results //The following is just in plain HTML for testing, but you can change to JSON foreach($questions as $q) { echo "<b>{$q['question']} (ID: {$q['question_id']})</b><ul>\b"; foreach($q['answers'] as $a) { echo "<li>{$a}</li>\n"; } echo "</ul><br><br>\n"; } Quote Link to comment Share on other sites More sharing options...
maune Posted January 25, 2012 Author Share Posted January 25, 2012 Thank you for the suggestions and the prompt reply. Ok, I tried the code you suggested and I got "Unable to get questions", but I don't see where the problem could be. As far as the other statements. The quiz app only use 4 answers, but my table has 5. I was trying to get a random pick of 3 of the 4 incorrect answers, so in essence each time the user takes the quiz the answers to select from would be a bit different. In the table the answer that is marked the "correct" answer if there is a 1 in that field and if it is "incorrect" it is a 0. There is also a column that is marked "sort_order" in the table that is delineated 1-5, but the "correct/incorrect" answers are not arranged in a consistent fashion throughout the table. I'm totally up for cleaning the code. Thank you for the help. Quote Link to comment Share on other sites More sharing options...
Psycho Posted January 25, 2012 Share Posted January 25, 2012 Thank you for the suggestions and the prompt reply. Ok, I tried the code you suggested and I got "Unable to get questions", but I don't see where the problem could be. As far as the other statements. The quiz app only use 4 answers, but my table has 5. I was trying to get a random pick of 3 of the 4 incorrect answers, so in essence each time the user takes the quiz the answers to select from would be a bit different. In the table the answer that is marked the "correct" answer if there is a 1 in that field and if it is "incorrect" it is a 0. There is also a column that is marked "sort_order" in the table that is delineated 1-5, but the "correct/incorrect" answers are not arranged in a consistent fashion throughout the table. I'm totally up for cleaning the code. Thank you for the help. As I suspected as a possible cause, you query is failing. Could be a simple typ0 in a field name or something. You will need to check for the error and fix accordingly. Change the line that runs the query as follows to get some more info to debug the problem $result = mysql_query($query); if(!$result) { //die ('Unable to get questions.'); //Comment out to debug die("Query: $query<br>Error: " . mysql_error()); } As for the 4 questions vs. 5, MySQL is not very efficient at randomizing results. I would still follow the a similar process as before but when processing the array of results I would remove one of the incorrect answers. This would only require one additional line of code in what I provided previously //Randomize the questions and answers shuffle($questions); foreach($questions as &$question) { unset($question['answers'][rand(1, 4)]); // <== This will remove one of the incorrect answers before randomizing shuffle($question['answers']); } Quote Link to comment Share on other sites More sharing options...
maune Posted January 25, 2012 Author Share Posted January 25, 2012 Thank you. OK, now that I changed the code I'm getting this error: Query: SELECT q.question_id, q.question, a.answer FROM wp_mtouchquiz_question q, JOIN wp_mtouchquiz_answer a ON q.ID = a.QUESTION_ID WHERE q.quiz_id = 1 ORDER BY question_id ASC, correct DESC Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'JOIN wp_mtouchquiz_answer a ON q.ID = a.QUESTION_ID WHERE q.quiz_i' at line 3 I ran the script through a syntax checker for my version of MySQL and I got no errors. Also I tried an INNER JOIN function (as per http://www.w3schools.com/sql/sql_join_inner.asp), but that didn't do anything either...... I included a small dump of the two tables with this post. Maybe it will help with the resolution of the problem as well. 17425_.pdf 17426_.pdf Quote Link to comment Share on other sites More sharing options...
PaulRyan Posted January 25, 2012 Share Posted January 25, 2012 The SQL syntax error is clearly visible, obviously your syntax highlighter doesn't work, or you didn't actually do what you said, nonetheless: q, JOIN Notice the comma better the "q" and "JOIN"? Remove that, and you won't have the syntax error Regards, PaulRyan. Quote Link to comment Share on other sites More sharing options...
maune Posted January 26, 2012 Author Share Posted January 26, 2012 Thanks for that PaulRyan. I don't know what happened. So I tested out the script and changed some errors and I'm getting data. The problem now is that when I run the script I'm only getting the first question of the table to show up, an empty ID, and a completely random list of all the answers from the answer table. In looking at the answers there is no continuity in the output (all of the answers are random, there is no set of 4 answers that should be grouped together to a question in the table). Also the number of the ID is not showing up either. Here is what an abbreviated portion of the output looks like: A gene that encodes for a protein with 300 amino acids contains how many nucleotides? (ID:) Frontal lobe transcription of DNA Ribosomes Midbrain It accumulates in the green leaves Dendrites platelets Periplasm, membrane with a phospholipid bilayer, capsule, membrane with lipopolysaccharides. Stomach Here is what the code looks like at this time: <?php //Connect To Database $hostname=""; $username=""; $password=""; $dbname=""; $question_table="wp_mtouchquiz_question"; $answer_table="wp_mtouchquiz_answer"; $yourfield = "question"; $question = "question"; $answer = "answer"; $connection = mysql_connect($hostname, $username, $password); $lastQuestionID = -1; $str = ""; mysql_select_db($dbname, $connection); if(!$connection) { die('Unable to connect to database server.'); } if(!mysql_select_db($dbname, $connection)) { die('Unable to select database.'); } //Query for questions/answers $question_table="wp_mtouchquiz_question"; $answer_table="wp_mtouchquiz_answer"; $query = "SELECT q.id, q.question, a.answer FROM {$question_table} q JOIN {$answer_table} a ON q.ID = a.QUESTION_ID WHERE q.quiz_id = 1 ORDER BY question_id ASC, correct DESC"; $result = mysql_query($query); if(!$result) { //die ('Unable to get questions.'); //Comment out to debug die("Query: $query<br>Error: " . mysql_error()); } //Populate results into multi-dimensional array $questions = array(); while($row = mysql_fetch_array($result)) { if(!isset($questions[$row['question_id']])) { $questions[$row['question_id']] = array( 'question' => $row['question'], 'question_id' => $row['question_id'], 'answers' => array() ); } $questions[$row['question_id']]['answers'][] = $row['answer']; } //Randomize the questions and answers shuffle($questions); foreach($questions as &$question) { unset($question['answers'][rand(1, 4)]); // <== This will remove one of the incorrect answers before randomizing shuffle($question['answers']); } //NOW output the results //The following is just in plain HTML for testing, but you can change to JSON foreach($questions as $q) { echo "<b>{$q['question']} (ID:{$q['question_id']})</b><ul>"; foreach($q['answers'] as $a) { echo "<li>{$a}</li>\n"; } echo "</ul><br><br>\n"; } ?> Quote Link to comment Share on other sites More sharing options...
maune Posted January 26, 2012 Author Share Posted January 26, 2012 Thanks for that PaulRyan. I don't know what happened. So I tested out the script and changed some small syntax/spelling errors and I'm getting data. The problem now is that when I run the script I'm only getting the first question of the table to show up, an empty ID, and a completely random list of all the answers from the answer table. In looking at the answers there is no continuity in the output (all of the answers are random, there is no set of 4 answers that should be grouped together to a question in the table). Also the number of the ID is not showing up either. Here is what an abbreviated portion of the output looks like: A gene that encodes for a protein with 300 amino acids contains how many nucleotides? (ID:) Frontal lobe transcription of DNA Ribosomes Midbrain It accumulates in the green leaves Dendrites platelets Periplasm, membrane with a phospholipid bilayer, capsule, membrane with lipopolysaccharides. Stomach Here is what the code looks like at this time: <?php //Connect To Database $hostname=""; $username=""; $password=""; $dbname=""; $question_table="wp_mtouchquiz_question"; $answer_table="wp_mtouchquiz_answer"; $yourfield = "question"; $question = "question"; $answer = "answer"; $connection = mysql_connect($hostname, $username, $password); $lastQuestionID = -1; $str = ""; mysql_select_db($dbname, $connection); if(!$connection) { die('Unable to connect to database server.'); } if(!mysql_select_db($dbname, $connection)) { die('Unable to select database.'); } //Query for questions/answers $question_table="wp_mtouchquiz_question"; $answer_table="wp_mtouchquiz_answer"; $query = "SELECT q.id, q.question, a.answer FROM {$question_table} q JOIN {$answer_table} a ON q.ID = a.QUESTION_ID WHERE q.quiz_id = 1 ORDER BY question_id ASC, correct DESC"; $result = mysql_query($query); if(!$result) { //die ('Unable to get questions.'); //Comment out to debug die("Query: $query<br>Error: " . mysql_error()); } //Populate results into multi-dimensional array $questions = array(); while($row = mysql_fetch_array($result)) { if(!isset($questions[$row['question_id']])) { $questions[$row['question_id']] = array( 'question' => $row['question'], 'question_id' => $row['question_id'], 'answers' => array() ); } $questions[$row['question_id']]['answers'][] = $row['answer']; } //Randomize the questions and answers shuffle($questions); foreach($questions as &$question) { unset($question['answers'][rand(1, 4)]); // <== This will remove one of the incorrect answers before randomizing shuffle($question['answers']); } //NOW output the results //The following is just in plain HTML for testing, but you can change to JSON foreach($questions as $q) { echo "<b>{$q['question']} (ID:{$q['question_id']})</b><ul>"; foreach($q['answers'] as $a) { echo "<li>{$a}</li>\n"; } echo "</ul><br><br>\n"; } ?> Quote Link to comment Share on other sites More sharing options...
Psycho Posted January 26, 2012 Share Posted January 26, 2012 When creating a process such as this it is typically a best practice to do one thing, check your results, then do the next thing. Since you already had per-existing code what I provided was pretty much a full solution except for the final output. You should add some debugging code at specific points to validate that the results up to that point are correct. The first thing I would do is echo out the query then run it in PHPMyAdmin to ensure the results are what I expect. Next, I would add an echo inside the while loop to output each record to verify that it matched the results I got in PHPMyAdmin Third, I would add a print_r() on the array before and after the code to shuffle() the array. Then, just find out where the debugging output does not match what you expect. Determine the cause and fix it. Here is the code with some debugging lines added <?php //Connect To Database $hostname=""; $username=""; $password=""; $dbname=""; $question_table="wp_mtouchquiz_question"; $answer_table="wp_mtouchquiz_answer"; $yourfield = "question"; $question = "question"; $answer = "answer"; $connection = mysql_connect($hostname, $username, $password); $lastQuestionID = -1; $str = ""; mysql_select_db($dbname, $connection); if(!$connection) { die('Unable to connect to database server.'); } if(!mysql_select_db($dbname, $connection)) { die('Unable to select database.'); } //Query for questions/answers $question_table="wp_mtouchquiz_question"; $answer_table="wp_mtouchquiz_answer"; $query = "SELECT q.id, q.question, a.answer FROM {$question_table} q JOIN {$answer_table} a ON q.ID = a.QUESTION_ID WHERE q.quiz_id = 1 ORDER BY question_id ASC, correct DESC"; $result = mysql_query($query); ## DEBUGGING LING ## echo "Query: {$query}<br> Num Records " . mysql_num_rows($result) . "<br><br>\n"; if(!$result) { //die ('Unable to get questions.'); //Comment out to debug die("Query: $query<br>Error: " . mysql_error()); } //Populate results into multi-dimensional array $questions = array(); while($row = mysql_fetch_assoc($result)) { ## DEBUGGING LING ## echo implode(" : ", $row) . "<br>\n"; if(!isset($questions[$row['question_id']])) { $questions[$row['question_id']] = array( 'question' => $row['question'], 'question_id' => $row['question_id'], 'answers' => array() ); } $questions[$row['question_id']]['answers'][] = $row['answer']; } ## DEBUGGING LING ## echo "Array before randomizing:<br><pre>" . print_r($questions, true) . "</pre><br>\n"; //Randomize the questions and answers shuffle($questions); foreach($questions as &$question) { unset($question['answers'][rand(1, 4)]); // <== This will remove one of the incorrect answers before randomizing shuffle($question['answers']); } ## DEBUGGING LING ## echo "Array after randomizing:<br><pre>" . print_r($questions, true) . "</pre><br>\n"; //NOW output the results //The following is just in plain HTML for testing, but you can change to JSON foreach($questions as $q) { echo "<b>{$q['question']} (ID:{$q['question_id']})</b><ul>"; foreach($q['answers'] as $a) { echo "<li>{$a}</li>\n"; } echo "</ul><br><br>\n"; } ?> Quote Link to comment Share on other sites More sharing options...
maune Posted January 26, 2012 Author Share Posted January 26, 2012 Thanks Psycho. I ran the code with the various debug parameters and, it seems like the problem is with the first array. The query is grabbing data from the proper location, and the while loop is functioning wonderfully! The id:question:answer is matching up as it should. When we get to the first array that is where the output fails. It only shows the first question in the table and the question_id (which are matched up properly), and then all of the answers from the answer_table, however they are in order and clustered in groups of 5 (as they should be up until this time). This is what the array debug output looks like: Array before randomizing: Array ( [] => Array ( [question_id] => 4 [question] => A gene that encodes for a protein with 300 amino acids contains how many nucleotides? [answers] => Array ( [0] => 900 [1] => 300 [2] => 100 [3] => 1200 [4] => 600 [5] => messenger RNA [6] => DNA [7] => transfer DNA [8] => ribosomal proteins [9] => amino acids When you look at the output after the shuffle function, there is the same problem, in that it's showing only the first question and question_id, but the answer output is totally shuffled and not formed in a coherent cluster of 4 answers. Quote Link to comment Share on other sites More sharing options...
Psycho Posted January 26, 2012 Share Posted January 26, 2012 It looks like the problem is that the 'key' for the question record in the array is not getting set correctly. Looks like it is an empty string. So, each question is determined to be the same based upon that value. The code is supposed to use the question ID as the key. I do see that the question ID is correctly set as one of the sub values in the array, but it is not set as the key for the array element. I thought there might be a typo in the variable/key name in the logic to create the key, but I've reviewed it several times and don't see a problem. Try this revision of the while loop: while($row = mysql_fetch_assoc($result)) { ## DEBUGGING LING ## echo implode(" : ", $row) . "<br>\n"; $qID = $row['question_id']; if(!isset($questions[$qID])) { $questions[$qID] = array( 'question' => $row['question'], 'question_id' => $qID, 'answers' => array() ); } $questions[$qID]['answers'][] = $row['answer']; } Quote Link to comment Share on other sites More sharing options...
maune Posted January 26, 2012 Author Share Posted January 26, 2012 GREAT!!! It's working fine now. I don't know why defining the $qID had to occur, but it worked. The shuffle is perfect too. Psycho you are AWESOME!! Now it's off to JSON land to try and get that worked out now One final couple of questions. 1) What would be the best option for making sure the "correct" answer is always one of the 4 choices? 2) Where is the best place to define the # of questions in the output? 3) Is it possible to replace the question_id number in the shuffled output to be that of the # the question was in the array? I know this value will change each time the script is run, but that way when it is picked up by the quiz engine the questions will always be randomized and the user will have a different Quote Link to comment Share on other sites More sharing options...
Psycho Posted January 26, 2012 Share Posted January 26, 2012 1) What would be the best option for making sure the "correct" answer is always one of the 4 choices? This should already being taken care of in the code I provided. The DB results are sorted such that the correct answer for each question will be listed first. Then in the code that shuffles the questions it FIRST removes one of the incorrect answers using unset($question['answers'][rand(1, 4)]) Since the correct answer will have an index of 0 it would never be removed 2) Where is the best place to define the # of questions in the output? 3) Is it possible to replace the question_id number in the shuffled output to be that of the # the question was in the array? I know this value will change each time the script is run, but that way when it is picked up by the quiz engine the questions will always be randomized and the user will have a different 2) Where is the best place to define the # of questions in the output? Good question. You can't simply LIMIT your results since you are getting more results than you have questions. You could always multiply the number of questions you want by 5 since all the questions have 5 answers and use that in your LIMIT. But, that's a poor solution because you may want o add more answers in the future. I would probably implement a subquery. But, then the question is do you want them in order or randomized. As I stated before MySQL does a poor job of randomizing. There are solutions but I don't have them memorized and am not going to take the time to look them up right now. But, if your database of questions would be relatively small you can use ORDER BY RAND() SELECT q.id, q.question, a.answer FROM {$question_table} q JOIN {$answer_table} a ON q.ID = a.QUESTION_ID WHERE q.id IN (SELCT id FROM {$question_table} WHERE quiz_id = 1 ORDER BY RAND() LIMIT $question_count) ORDER BY question_id ASC, correct DESC 3) Is it possible to replace the question_id number in the shuffled output to be that of the # the question was in the array? I know this value will change each time the script is run, but that way when it is picked up by the quiz engine the questions will always be randomized and the user will have a different Huh? Not sure what you are wanting. I believe the shuffle() command resets all the keys in the array. So, question #1 (as given to the user) will have an index of 1, question #2 will be 1 and so forth. So, it already tells you the order that they were given to the user. Quote Link to comment Share on other sites More sharing options...
maune Posted February 21, 2012 Author Share Posted February 21, 2012 Thank you for all of the help Psycho. I think that the limit option with 5 x the number of questions is the way to go. I've been working on the JSON output that I need for the app to work, and I can't get it to come out right. I've tried json encode, but it doesn't put it in the proper format either, however the data is parsed correctly. Here is a copy of what the output format has to be: {"childItems":[ {"itemId":"question1", "itemType":"BT_questionItem", "questionText":"What is the capital city of Nevada?", "correctAnswerText":"Carson City", "incorrectText1":"Las Vegas", "incorrectText2":"Reno", "incorrectText3":"Tahoe", "imageURLSmallDevice":"http://www.mywebsite.com/quizImage1.png", "imageURLLargeDevice":"http://www.mywebsite.com/quizImage1.png" }, {"itemId":"question2", "itemType":"BT_questionItem", "questionText":"What is the capital city of California?", "correctAnswerText":"Sacramento", "incorrectText1":"Modesto", "incorrectText2":"Monterey", "incorrectText3":"Los Angeles", "imageURLSmallDevice":"http://www.mywebsite.com/quizImage2.png", "imageURLLargeDevice":"http://www.mywebsite.com/quizImage2.png" } ] } The "imageURLSmallDevince" and "imageURLLargeDevice" just need to have a custom value entered in them (same url for both). I don't have a place in the database with this url. After I use json encode this is what I have (very small dump of a large set): [ { "question": "The two DNA strands attached to a single centromere during metaphase of mitosis are called?", "question_id": "125", "answers": [ "centrioles", "chromatids", "chromosomes", "sarcomere" ] }, { "question": "Which of the following is not a component of a typical bacterial cell?", "question_id": "299", "answers": [ "Flagella", "RNA", "Ribosomes", "Cilia" ] }, { "question": "The dark reactions of photosynthesis occur", "question_id": "95", "answers": [ "only at night", "when light is available", "only after one hour of darkness", "in green plants only" ] }, { "question": "In a redox reaction the", "question_id": "28", "answers": [ "reducing agent is the most electronegative", "reducing agent accepts electrons", "substance that is oxidized loses energy", "substance that is reduced loses energy" ] }, { "question": "Pores in the nuclear envelope serve all of the following functions except?", "question_id": "30", "answers": [ "allows amino acids to enter the nucleus", "allows ribosomal components to exit the nucleus", "allow the export of proteins", "allows the import of proteins" ] } ] Any thoughts on how I can encode the in the proper fashion? Is it easiest to set it up in strings? If so, how do I define the correct and incorrect answers as needed in the above example? Thank you in advance for the help. Quote Link to comment Share on other sites More sharing options...
Psycho Posted February 21, 2012 Share Posted February 21, 2012 I've never worked with JSON encode. But, now that you know you are getting the correct data, you should probably create a new thread about formatting the output into the format you need. I would provide an example of the data you have and the format you need it in. Quote Link to comment Share on other sites More sharing options...
maune Posted February 21, 2012 Author Share Posted February 21, 2012 Thank you. One last question for you. What if I didn't use the JSON encode and tried something like this: { $str .= "{\"childItems\":["; $str .= "{\"itemId\":\"question" . $row["qID"] . "\","; $str .= "\"itemType\":\"BT_questionItem\","; $str .= "\"questionText\":\"" . $row["question"] . "\","; if($row["answers"] == 0) { $str .= "\"correctAnswerText\":\"" . $row["answer"] . "\","; } // incorrect if ($row["answers"] ==1) { $str .= "\"incorrectText1\":\"" . $row["answer"] . "\","; } // incorrect if ($row["answers"] ==2) { $str .= "\"incorrectText2\":\"" . $row["answer"] . "\","; } // incorrect if ($row["answers"] ==3) { $str .= "\"incorrectText3\":\"" . $row["answer"] . "\","; } {$str = strip_tags($str); } $str .= "\"imageURLSmallDevice\":\"http://www.myURL.com\","; $str .= "\"imageURLLargeDevice\":\"http://www.myURL.com\"},"; // remove last comma $str = substr($str,'',-1); $str .= "] }"; echo $str; } When I run this, I get a single line of output: {"childItems":[{"itemId":"question","itemType":"BT_questionItem","questionText":"","correctAnswerText":"","imageURLSmallDevice":"http://www.mURL.com","imageURLLargeDevice":"http://www.myURL.com"}] } The data output is a valid JSON format, but there's is a problem putting the data from the array of question, question_id and answers into the strings. What do you think about this? If you don't think that this will work I'll make a new post about it. Thanks. Quote Link to comment Share on other sites More sharing options...
Psycho Posted February 21, 2012 Share Posted February 21, 2012 I really don't know and just don't have the time to get into it today. Besides, a new thread would be best since I don't want to give you a sub-optimal solution. Best that someone with experience with JSON help you. Quote Link to comment 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.