php - How to count text inside an array?
Get the solution ↓↓↓In my MySQL table (userdata) there's a column named "options". In that column user responses are stored after they complete a quiz. Sample data pertaining to a user is given below:
{"correctness":{"question_id_209":false,"question_id_208":true,"question_id_207":true,"question_id_206":false,"question_id_205":true},"user_answered":{"question_id_209":"830","question_id_208":"826","question_id_207":"822","question_id_206":"818","question_id_205":"815"},"passed_time":"13 seconds","user_points":3,"max_points":5,"attributes_information":[],"calc_method":"by_correctness"}
Now I want to search this array for the word "true" and want to count the word. I started with this, but don't know what to do next:
$query="SELECT options FROM userdata WHERE user_id=1";
$result= mysqli_query($conn,$query);
Answer
Solution:
If you want to only count how many correct answers the user had for display purposes, here is what you should do following your example:
$row = mysqli_fetch_assoc($result);
$data = json_decode($row['options'], true);
$correctAnswers = array_filter($data['correctness'], function($question) {
return $answer === true;
});
$total = count($correctAnswers);
But if you want to do a SQL query, then it would be more complicated. For that you might want to take a look at this page: https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html
I hope it helps.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: filter_sanitize_string
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.