Creating php json object array inside of array - php

I'm having trouble trying to figure out how would I create a Php json object that has an array inside of array. I have been working on this for hours and can't figure it out. Should I use oject inside my while loop and add array?
I Would like to have my answer array inside my question array like this.
{
"success":true,
"total":2,
"question":[
{
"id":"1",
"product":"The Product",
"question":"Some question here"
"answer":[
{
"answer_id":"1",
"answer":"First answer",
"is_correct":"1",
"question_id":"1"
},
{
"answer_id":"2",
"answer":"Second answer",
"is_correct":"1",
"question_id":"1"
}
]
}
],
"question":[
{
"id":"2",
"product":"The Product",
"question":"Some question here"
"answer":[
{
"answer_id":"1",
"answer":"First answer",
"is_correct":"0",
"question_id":"1"
},
{
"answer_id":"2",
"answer":"Second answer",
"is_correct":"1",
"question_id":"1"
}
]
}
],
See code below.
$question_arr = array();
$answer_arr = array();
//Question table results
$sql = "SELECT * FROM Questions WHERE product='".$product."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$row_question_array['id'] = $row['ID'];
$row_question_array['product'] = $row['product'];
$row_question_array['question'] = $row['question'];
array_push($question_arr,$row_question_array);
//Anwser table results
$sql2 = "SELECT * FROM Answers WHERE question_id='".$row['ID']."'";
$result2 = $conn->query($sql2);
while($row2 = $result2->fetch_assoc()) {
$row_anwser_array['answer_id'] = $row2['answer_id'];
$row_anwser_array['product'] = $row2['product'];
$row_anwser_array['answer'] = $row2['answer'];
$row_anwser_array['is_correct'] = $row2['is_correct'];
$row_anwser_array['question_id'] = $row2['question_id'];
array_push($answer_arr,$row_anwser_array);
}
}
} else {
echo "question 0 results";
}
$myObj->success = true;
$myObj->total = $result->num_rows;
$myObj->question = $question_arr;
$myObj->answer = $answer_arr;
//echo json_encode($question_arr);
//echo json_encode($answer_arr);
echo json_encode($myObj);

There's no need to create two separate $question_arr or $answer_arr arrays. Instead, just create one empty result array $resultArr and refactor your code in the following way,
$resultArr = array();
$sql = "SELECT * FROM Questions WHERE product='".$product."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$resultArr = array('success' => true, 'total' => $result->num_rows);
while($row = $result->fetch_assoc()) {
$resultArr['question'][$row['ID']] = array('id' => $row['ID'], 'product' => $row['product'], 'question' => $row['question']);
//Anwser table results
$sql2 = "SELECT * FROM Answers WHERE question_id='".$row['ID']."'";
$result2 = $conn->query($sql2);
while($row2 = $result2->fetch_assoc()) {
$resultArr['question'][$row['ID']]['answer'][] = $row2;
}
}
$resultArr['question'] = array_values($resultArr['question']);
} else {
$resultArr = array('success' => false, 'total' => 0);
echo "question 0 results";
}
echo json_encode($resultArr);

Related

php mysql_fetch_assoc to json encode

I am Using Following code php array to encode Json
$query = "SELECT * FROM register WHERE email='$email'AND password='$password'AND status!='0'";
$result = mysql_query($query) or die('Errant query: ' . $query);
$numResults = mysql_num_rows($result);
if ($numResults > 0)
{
$data = array();
while ($row = mysql_fetch_assoc($result))
{
$data = $row;
}
echo json_encode($data);
}
IT gives Me result like
{"id":"26","fname":"Shankar","lname":"Salunkhe","category_name":"2"}
But I wanted To result like
{"SignIn":[{"id":"26","fname":"Shankar","lname":"Salunkhe","category_name":"2"}],"errors":[],"totalNumberOfRecords":1,"responseCode":"00000"}
How Can I do That
Or Suggest Me any other Method to do that
You need to do something like below to get the desired output.
$query = "SELECT * FROM register WHERE email='$email'AND password='$password'AND status!='0'";
$result = mysql_query($query) or die('Errant query: ' . $query);
$numResults = mysql_num_rows($result);
if ($numResults > 0)
{
$data = array();
while ($row = mysql_fetch_assoc($result))
{
$data[] = $row;
}
$result = ['SignIn' => $data, 'totalNumberOfRecords' => $numResults, 'errors' => [], 'responseCode' => 0000];
echo json_encode($result);
exit;
}
You have to store all information in a array to get what you want.
For example,
$data = array("id" =>"26","fname"=>"Shankar","lname"=>"Salunkhe","category_name"=>"2");
$array = array("SignIn" => $data, "errors" => [], "totalNumberOfRecords" => 1,"responseCode" => "00000");
$result = json_encode($array);

Fetching record from two table and convert into json

Hi I'm new in PHP and trying to get the below response using php sql but i'm not be able to find the such desire output
[{"Id":1, "name": "India", "Cities":[{"Id":1, "Name":"Mumbai", "country_id":1}, {"Id":2,"Name":"Delhi","country_id":1},
"id":3,"Name":Banglore","country_id":1}, {"Id":2, "Name":"USA", "Cities":[{"Id":6, "Name":"New York", "country_id":2},.....
I have two tables one is country based and other is city based.
I tried
<?php
include_once("config.inc.php");
$sql = "SELECT * FROM country";
$sqlCity = "SELECT * FROM city";
$cityQuery = mysqli_query($conn, $sqlCity);
$sqlQuery = mysqli_query($conn, $sql);
$mainArray = array();
if(mysqli_num_rows($cityQuery) > 0 ){
$cityResponse = array();
while($resCity = mysqli_fetch_assoc($cityQuery)){
$cityResponse[] = $resCity;
}
if(mysqli_num_rows($sqlQuery) > 0 ){
$response = array();
while($res = mysqli_fetch_assoc($sqlQuery)){
$response[] = $res;
}
foreach($cityResponse as $city){
foreach($response as $country){
if($city['country_id'] == $country['id']){
$mainArray = array("Cities" => $city);
}
}
}
echo '{"response": '.json_encode($response).', '.json_encode($mainArray).' "success": true}';
}
}else{
echo '{"response": '.json_encode($response).' "success": false}';
}
?>
currently my response showing
{"response": [{"id":"1","name":"India"},{"id":"2","name":"USA"},{"id":"3","name":"UK"}], {"Cities":{"id":"15","name":"Manchester","country_id":"3"}} "success": true}
For detail code explanation check the inline comments
Modify the SQL query with related column names
The memory you have to take care. By default memory limit in php is 128MB in 5.3
Check the code and let me know the result
<?php
$data = array();
//include your database configuration files
include_once("config.inc.php");
//execute the join query to fetch the result
$sql = "SELECT country.country_id, country.name AS country_name,".
" city.city_id, city.name AS city_name FROM country ".
" JOIN city ON city.country_id=country.country_id ".
" ORDER BY country.country_id ";
//execute query
$sqlQuery = mysqli_query($conn, $sql) or die('error exists on select query');
//check the number of rows count
if(mysqli_num_rows($sqlQuery) > 0 ){
//country id temprory array
$country_id = array();
//loop each result
while($result = mysqli_fetch_assoc($sqlQuery)){
//check the country id is already exist the only push the city entries
if(!in_array($result['country_id'],$country_id)) {
//if the city is for new country then add it to the main container
if(isset($entry) && !empty($entry)) {
array_push($data, $entry);
}
//create entry array
$entry = array();
$entry['Id'] = $result['country_id'];
$entry['name'] = $result['country_name'];
$entry['Cities'] = array();
//create cities array
$city = array();
$city['Id'] = $result['city_id'];
$city['name'] = $result['city_name'];
$city['country_id'] = $result['country_id'];
//append city entry
array_push($entry['Cities'], $city);
$country_id[] = $result['country_id'];
}
else {
//create and append city entry only
$city = array();
$city['Id'] = $result['city_id'];
$city['name'] = $result['city_name'];
$city['country_id'] = $result['country_id'];
array_push($entry['Cities'], $city);
}
}
}
//display and check the expected results
echo json_encode($data);
use like this
<?php
include_once("config.inc.php");
$sql = "SELECT * FROM country";
$sqlCity = "SELECT * FROM city";
$cityQuery = mysqli_query($conn, $sqlCity);
$sqlQuery = mysqli_query($conn, $sql);
$mainArray = array();
if(mysqli_num_rows($cityQuery) > 0 ){
$cityResponse = array();
while($resCity = mysqli_fetch_assoc($cityQuery)){
$cityResponse[] = $resCity;
}
if(mysqli_num_rows($sqlQuery) > 0 ){
$response = array();
while($res = mysqli_fetch_assoc($sqlQuery)){
$response[] = $res;
}
foreach($cityResponse as $city){
foreach($response as $country){
if($city['country_id'] == $country['id']){
$mainArray = array("Cities" => $city);
}
}
}
echo json_encode(array('result'=>'true','Cities'=>$mainArray));
}
}else{
echo json_encode(array('result'=>'false','Cities'=>$response));
}
?>
You can use try this. It actually works for me and it's cool. You can extend to 3 or more tables by editing the code.
try {
$results = array();
$query = "SELECT * FROM country";
$values = array();
$stmt = $datab->prepare($query);
$stmt->execute($values);
while($country = $stmt->fetch(PDO::FETCH_ASSOC)){
$cities = null;
$query2 = "SELECT * FROM city WHERE country_id = ?" ;
$values2 = array($country['id']);
$stmt2 = $datab->prepare($query2);
$stmt2->execute($values2);
$cities = $stmt2->fetchAll();
if($cities){
$country['cities'] = $cities;
} else {
$country['cities'] = '';
}
array_push($results, $country);
}
echo json_encode(array("Countries" => $results));
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}

Convert/query array into JSON with PHP

I have a SELECT query that results in something like this:
USER_ID: 000030 USERNAME: Oprah RATING: 5
USER_ID: 000033 USERNAME: Pitbull RATING: 8
What I need is to display it in this form:
[[{"USER_ID":"000030","USERNAME":"Oprah","RATING":"5"},{"USER_ID":"000033","USERNAME":"Pitbull","RATING":"8"}]]
Generally I get this desired result with this SELECT:
try {
$stmt = $conn->prepare("SELECT USER_ID, USERNAME, RATING FROM table");
$stmt -> execute(array($userid));
while($row = $stmt->fetchAll(PDO::FETCH_ASSOC)) {
$output[] = $row;
}
}
print(json_encode($output));
But this time I had to get the result in this form:
try {
$stmt = $conn->prepare("SELECT USER_ID, USERNAME, RATING FROM table");
$stmt -> execute(array($userid));
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
//$output[] = $row;
$row2[$i][$j] = $row['USER_ID'];
$j++;
$row2[$i][$j] = $row['USERNAME'];
$j++;
$row2[$i][$j] = $row['RATING'];
$i++;
$j=0;
}
}
How can I convert it into the desired form or form the query to produce it?
I tried these:
print(json_encode($row2));
[["000030","Oprah","5"],["000033","Pitbull","8"]]
$output[] = $row2;
print(json_encode($output));
[[["000030","Oprah","5"],["000033","Pitbull","8"]]]
For json_encode() to produce a json string that includes the associative indices, they need to be in the array you are encoding. If the indices are 0, 1, 2, etc., the indices will not show up in the json string.
Try this:
$i=0;
while(...) {
$row2[$i]['USER_ID'] = $row['USER_ID'];
$row2[$i]['USERNAME'] = $row['USERNAME'];
$row2[$i]['RATING'] = $row['RATING'];
$i++;
}
...
print_r(json_encode($row2));
Consider this PHP snippet for clarification.
Alternative methods of building array:
while(...) {
$row2[] = array(
'USER_ID' = $row['USER_ID'],
'USERNAME' = $row['USERNAME'],
'RATING' = $row['RATING']
);
}
// OR
$i=0;
while(...) {
foreach ($row as $key => $val) {
$row2[$i][$key] = $val;
}
$i++;
}
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$output[] = array("USER_ID" => $row["USER_ID"],
"USERNAME" => $row["USERNAME"],
"RATING" => $row["RATING"],
);
}
print(json_encode($output));

How to convert mysqli_fetch_assoc results into json format?

i am trying to convert the result of my query into a json format so i can grap it with jquery in another file. I dont get any errors but its not recognised as json.
$patientquery = mysqli_query($connect, "SELECT * FROM login WHERE assignedTo='$logID'");
$numrows = mysqli_num_rows($patientquery);
if($numrows > 0)
{
while($rows = mysqli_fetch_assoc($patientquery))
{
$dbloginID = $rows['loginID'];
$dbname = $rows['name'];
$result[] = array('patient'=>array('id' => $dbloginID, 'name' => $dbname));
}
}
else
{
$result[] = 'No Patients yet';
}
echo json_encode($result);
please try this:
$patientquery = mysqli_query($connect, "SELECT * FROM login WHERE assignedTo='$logID'");
$numrows = mysqli_num_rows($patientquery);
$result = array();
if($numrows > 0)
{
while($rows = mysqli_fetch_assoc($patientquery))
{
$dbloginID = $rows['loginID'];
$dbname = $rows['name'];
$result['patient'][] = array('id' => $dbloginID, 'name' => $dbname);
}
}
else
{
$result[] = 'No Patients yet';
}
echo json_encode($result);
You should declare $result outside while loop like this
$result = array();

Creating an associative array in PHP from sql results, for json

I'm trying to create an associative array from sql results for json_encode.
here's my code:
$timelineQuery = "SELECT * FROM timeline_table";
$contentQuery = "SELECT * FROM content_table";
$picQuery = "SELECT * FROM pic_table";
$sql = mysql_query($timelineQuery) or die(mysql_error());
$sql2 = mysql_query($contentQuery) or die(mysql_error());
$sql3 = mysql_query($picQuery) or die(mysql_error());
$mainArray = array(
'timeline' => $timelineArray = array(
'content' => $contentArray = array(
'pictures' => $picArray = array(),
),
),
);
while($row = mysql_fetch_assoc($sql)) {
$timelineArray[] = $row;
}
while($row2 = mysql_fetch_assoc($sql2)) {
$contentArray[] = $row2;
}
while($row3 = mysql_fetch_assoc($sql3)) {
$picArray[] = $row3;
}
echo stripslashes(json_encode($mainArray));
If I json_encode my $mainArray as it is, the returned json has the syntax I'm looking for, but I've not been able to fill the array without adding it to the end of my array.
{"timeline":{"content":{"pictures":[]}}}
first:
while($row = mysql_fetch_assoc($sql)) {
$timelineArray[] = $row;
}
while($row2 = mysql_fetch_assoc($sql2)) {
$contentArray[] = $row2;
}
while($row3 = mysql_fetch_assoc($sql3)) {
$picArray[] = $row3;
}
then:
$mainArray = array(
'timeline' => $timelineArray = array(
'content' => $contentArray = array(
'pictures' => $picArray = array(),
),
),
);
echo stripslashes(json_encode($mainArray));
you defined your array with empty arrays and didn't renew it's states.

Categories