Create JSON Structure in PHP - php

$query = "SELECT `contact_id`, `user_id`, `date_backup`, `first_name`, `last_name` FROM tbl_contacts WHERE date(`date_backup`) = (SELECT MAX(date(`date_backup`)) FROM tbl_contacts WHERE `user_id`= '$userId' ) ORDER BY `date_backup` DESC, `contact_id` ASC";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) {
$contacts = array(array());
$contactId = $row['contact_id'];
$names["first_name"] = $row['first_name'];
$names["last_name"] = $row['last_name'];
$contacts["names"][] = $names;
// Phone
$phoneQuery = "SELECT * FROM tbl_phone_details WHERE contact_id = '$contactId' AND date(`date_backup`) = (SELECT MAX(date(`date_backup`)) FROM tbl_phone_details WHERE `contact_id`= '$contactId')";
$phoneResult = mysql_query($phoneQuery);
$total = mysql_affected_rows();
if($total >= '1') {
while($phoneRow = mysql_fetch_assoc($phoneResult)) {
$phones["phone_number"] = $phoneRow['phone_number'];
$phones["phone_type"] = $phoneRow['phone_type'];
$contacts["phones"][] = $phones;
}
} else {
$contacts["phones"][] = array();
}
// Email
$emailQuery = "SELECT * FROM `tbl_email_details` WHERE `contact_id` = '$contactId' AND date(`date_backup`) = (SELECT MAX(date(`date_backup`)) FROM tbl_email_details WHERE `contact_id`= '$contactId')";
$emailResult = mysql_query($emailQuery);
$total = mysql_affected_rows();
if($total >= '1') {
while($emailRow = mysql_fetch_assoc($emailResult)) {
$emails["email_address"] = $emailRow['email_address'];
$emails["email_type"] = $emailRow['email_type'];
$contacts["emails"][] = $emails;
}
} else {
$contacts["emails"][] = array();
}
// Address
$addressQuery = "SELECT * FROM `tbl_address_detail` WHERE `contact_id` = '$contactId' AND date(`date_backup`) = (SELECT MAX(date(`date_backup`)) FROM tbl_address_detail WHERE `contact_id`= '$contactId')";
$addressResult = mysql_query($addressQuery);
$total = mysql_affected_rows();
if($total >= '1') {
while($addressRow = mysql_fetch_assoc($addressResult)) {
$address["street"] = $addressRow['street'];
$address["city"] = $addressRow['city'];
$address["state"] = $addressRow['state'];
$address["zip"] = $addressRow['zip'];
$address["country"] = $addressRow['country'];
$address["addressType"] = $addressRow['addressType'];
$contacts["address"][] = $address;
}
} else {
$contacts["address"][] = array();
}
$contectInfoJson["contacts"][] = $contacts;
}
$allContactJson["AllContacts"] = $contectInfoJson;
header('Content-Type: application/json');
echo json_encode($allContactJson);
OUTPUT OF CODE :-
AllContacts: {
userId: "15",
contacts: [
{
0: [ ], // Not needed
names: [ // Instead of array i need simple object of names
{
first_name: "ABC",
last_name: "XYZ"
}
],
phones: [
{
phone_number: "+911234567890",
phone_type: "Work"
},
{
phone_number: "+919876543210",
phone_type: "Home"
}
],
emails: [
[ ] //This is also extra and not needed.
],
address: [
{
street: "India",
city: "",
state: "",
zip: "",
country: "",
addressType: ""
}
]
},
REQUIRED OUTPUT:-
AllContacts: {
userId: "15",
contacts: [
{
names:
{
first_name: "ABC",
last_name: "XYZ"
},
phones: [
{
phone_number: "+911234567890",
phone_type: "Work"
},
{
phone_number: "+919876543210",
phone_type: "Home"
}
],
emails: [],
address: [
{
street: "India",
city: "",
state: "",
zip: "",
country: "",
addressType: ""
}
]
},
I am facing 2-3 small problem in the code.
First is that i am getting 0 : [] on every start of the object.
2nd one is names is array and i want it to be object not array.
3rd is emails :[ [] ], i want blank array if data is not available, but i am getting array inside array. I just want emails :[].

Replace $contacts = array(array()); with $contacts = array();. Should remove 0 : [].
$contacts["emails"][] = array(); is triggered probably, so try to replace it with $contacts["emails"] = array();
Replace $contacts["names"][] = $names; with $contacts["names"] = $names;

Related

how to remove extra square bracket in json format?

this is my json response:
{"risultato":"1","ris":[[{"pda":"788","num1":"83","num2":"10","num3":"207410"},{"pda":"232","num1":"83","num2":"14","num3":"204935"}]]}
as you can see there is an extra square bracket, how can I remove it?
the result I would like this:
{"risultato":"1","ris":[{"pda":"788","num1":"83","num2":"10","num3":"207410"},{"pda":"232","num1":"83","num2":"14","num3":"204935"}]}
php:
$stmtcarte = $connection->prepare("SELECT GROUP_CONCAT(concat.pda) as pda, GROUP_CONCAT(concat.num1) as num1,GROUP_CONCAT(concat.num2) as num2, GROUP_CONCAT(concat.num3) as num3 FROM (SELECT pda, num1, num2, num3 FROM giocatori WHERE categoria=? ORDER BY RAND() LIMIT 2 ) concat");
$categoria=$categoriaselezionata;
$stmtcarte->bind_param("s",$categoria);
$stmtcarte->execute();
$risultatocarte = $stmtcarte->get_result();
$numero_giocatori = $risultatocarte->num_rows;
$result=array("risultato"=>"1", "ris"=>"");
while($rispostacarte=$risultatocarte->fetch_assoc()){
$result['ris']=array($rispostacarte);
$ris = $result["ris"][0];
$tempRis = [];
foreach ($ris as $key => $value) {
$explodedArray = explode(",", $value);
$length = count($explodedArray);
for ($i=0; $i < $length ; $i++) {
$tempRis[$i][$key] = $explodedArray[$i];
}
}
$result["ris][0] = $tempRis;
echo json_encode($result);
}
$stmtcarte->close();
You can use simple code like:
<?php
$query = "SELECT pda, num1, num2, num3
FROM giocatori WHERE categoria=?
ORDER BY RAND()
LIMIT 2";
// get DB data using PDO
$stmt = $pdo->prepare($query);
$stmt->execute([$category]);
$risultato = [
'risultato' => 1,
'ris'=>[]
];
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$risultato['ris'][] = $row;
}
print_r(json_encode($risultato, JSON_PRETTY_PRINT));
Test PHP & MySQL code here
Result:
{
"risultato": 1,
"ris": [
{
"pda": "788",
"num1": "83",
"num2": "10",
"num3": "207410"
},
{
"pda": "232",
"num1": "83",
"num2": "14",
"num3": "204935"
}
]
}

Insert data to array using while loop php

I am trying to insert data from database into an array, using while loop, here is my database:
id resulst
152556 0
152555 1
152553 1
152552 0
152551 1
152550 0
152549 1
Here is the code that I did:
$output = [
"online" => 0,
"success" => 0,
"servers" => []
];
$mini_result = $db->query("SELECT * FROM `sessions` WHERE status = '1' LIMIT 5");
while( $result = $mini_result->fetch()){
$output['servers']['mini_result'] = [
$result['id'] => $result['result']
];
}
$output["online"] = 1;
$output["success"] = 1;
echo json_encode($output, JSON_PRETTY_PRINT );
Output:
{
online: 1,
success: 1,
servers: {
mini_result: {
152556: "0"
}
}
}
It only prints 1 element, not 5 as I would like. This is the output I want:
{
online: 1,
success: 1,
servers: {
mini_result: {
152556: "0",
152555: "1",
152553: "1",
152552: "0",
152551: "1"
}
}
}
Can you help me?
You overwrite the result on every loop of the loop. What you need to do is:
while($result = $mini_result->fetch()) {
$output['servers']['mini_result'][$result['id']] = $result['result'];
}
This does get quickly quite confusing. You can simplify it, like this:
$miniResult = [];
while($result = $mini_result->fetch()) {
$miniResult[$result['id']] = $result['result'];
}
$output['servers']['mini_result'] = $miniResult;
This what u need:
$mini_result = $db->query("SELECT * FROM `sessions` WHERE status = '1' LIMIT 5");
$output['servers']['mini_result'] = [];
while( $result = $mini_result->fetch()){
$output['servers']['mini_result'][$result['id']] = $result['result'];
}

Grouping JSON output according to specific mysql column

I have a mysql table (name:"messages") that has three columns as below:
messageID, fromUserID, content
I wish to have a json output using php script like following format; I need to seprate messages of each user (fromUserID column).
JSONOutput:
{
"newCount":"x",
"messages":
[
{
"fromUserID":"x",
"messagesArray":
[
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"}
]
},
{
"fromUserID":"y",
"messagesArray":
[
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"}
]
},
{
"fromUserID":"z",
"messagesArray":
[
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"}
]
}
]
}
My PHP Script:
$query = mysqli_query($con,"SELECT * FROM messages ORDER BY fromUserID");
$outputArray = array();
$outputArray['hasNew'] = mysqli_num_rows($query);
$messagesArray = array();
if($query)
{
while($row = mysqli_fetch_assoc($query))
{
$MSGArray = array();
$messagesArray['fromUserID'] = $row['fromUserID'];
$MSGArray['messageID'] = $row['messageID'];
$MSGArray['content'] = $row['content'];
$messagesArray['MessagesArray'][] = $MSGArray;
}
$outputArray['Messages'][] = $messagesArray;
}
echo json_encode($outputArray);
But with above script I give a wrong result as below:
{
"hasNew":6,
"Messages":
[
{
"fromUserID":"24",
"MessagesArray":
[
{"messageID":"4","content":"test"},
{"messageID":"3","content":"test"},
{"messageID":"6","content":"test"},
{"messageID":"5","content":"test"},
{"messageID":"1","content":"test"},
{"messageID":"2","content":"test"}
]
}
]
}
My PHP Script just using last fromUserID value to grouping messages !!!
Please let me know where I'm wrong ...
Try it
if($query)
{
while($row = mysqli_fetch_assoc($query))
{
$MSGArray = array();
$messagesArray[$row['fromUserID']]['fromUserID'] = $row['fromUserID'];
$MSGArray['messageID'] = $row['messageID'];
$MSGArray['content'] = $row['content'];
$messagesArray[$row['fromUserID']]['MessagesArray'][] = $MSGArray;
}
foreach($messagesArray as $value) {
$outputArray['Messages'][] = $value;
}
}

Pass new php array key into json

I have 2 table users(id,userid,fn,ln) and userdetails(id,userid,image,history,location,activity)
And i have written a query for first table to retrieve all the data and i want only history and location ,from second table.
i have retrieved the array and i am sending it to json_encode.
Now i want to retrieve the history,location and create a new key History and i want to add history location values to history key.
I need a query and json format for these.
For particular user i need to retrieve is own history
In both tables user id in common
Thanks in advance
$sth = mysql_query("SELECT * FROM users");$result = mysql_fetch_assoc($sth);
$i=0;
foreach($result as $data) {
$final_array[$i]['id'] = $data['id'];
$final_array[$i]['email'] = $data['email'];
$final_array[$i]['fname'] = $data['fname'];
$final_array[$i]['lname'] = $data['lname'];
$sth2 = mysql_query("SELECT id,places,act FROM user_dates WHERE user_id= '".$data['email']."'");
$result2 = mysql_fetch_assoc($sth2);
$j=0;
$history_array = array();
foreach($result2 as $data2) {
$history_array[$j] = array("id" => $data2['id'],"places" => $data2['places'], "act " => $data2['act ']);
$j++;
}
$final_array[$i]['history'] = $history_array;
$i++;
}
echo json_encode($final_array);
[
{
"id": "81",
"user_id": "2011",
"fn": "asd.",
"ln": "wer",
"History": [
{
"id": "350",
"history": "make1",
"Location": "qwe"
}
]
},
{
"id": "82",
"user_id": "2012",
"fn": "asd1",
"ln": "wer1",
"History": [
{
"id": "350",
"history": "make2",
"Location": "qwe2"
}
]
}
]
Userdetails table contains multiple records per user. So you need to do sub query and get the results and then form a mulch-dimensional array. Finally, encode as a JSON.
$sth = $dbh->prepare("SELECT * FROM users");
$sth->execute();
$result = $sth->fetchAll();
$i=0;
foreach($result as $data) {
$final_array[$i]['id'] = $data['id'];
$final_array[$i]['userid'] = $data['userid'];
$final_array[$i]['fn'] = $data['fn'];
$final_array[$i]['ln'] = $data['ln'];
$sth2 = $dbh->prepare("SELECT location,activity FROM userdetails WHERE userid= ".$data['id']."");
$sth2->execute();
$result2 = $sth2->fetchAll();
$j=0;
$history_array = array();
foreach($result2 as $data2) {
$history_array[$j] = array("location" => $data2['location'], "activity " => $data2['activity ']);
$j++;
}
$final_array[$i]['history'] = $history_array;
$i++;
}
echo json_encode($final_array);

MySQL to nested JSON

This is almost exactly what I want, but that question hasn't been answered and it's been a year. I've managed to get close, I think, but numbers are being printed as keys. In my example it shows up on line 47, but it is repeated for every "course_name" in the actual file.
[
{
"school_name": "Projects",
"terms": [
{
"term_name":"category_name#1",
"departments": [
{
"department_name":"sub_category_name1",
"department_code":"category code text here",
"courses":[
{
"course_name": "project1",
"course_code":"project 1 code text goes here",
"sections":[
{
"section_code":"mike",
"unique_id":"xxx#mail.com"
},
{
"section_code":"dan",
"unique_id":"xxx#gmail.com"
}
]
},
{
"course_name": "project2",
"course_code":"project 2 code text goes here",
"sections":[
{
"section_code":"steve",
"unique_id":"xxx#mail.com"
},
{
"section_code":"chris",
"unique_id":"xxx#gmail.com"
}
]
}
]
},
{
"department_name": "sub_category_name2",
"department_code":"sub category description text goes here..",
"courses": {
-->>> "69": {
"course_name": "project3",
"course_code":"project3 code text goes here ",
"sections":[
{
"section_code":"Alex",
"unique_id":"xxx#gmail.com"
}
]
}
}
}
]
}
]
}
]
Here is the query I am using and an example of data being returned.
SELECT school_name, term_name, department_name, department_code, course_code, course_name, section_code, magento_course_id
FROM schools INNER JOIN term_names ON schools.id=term_names.school_id INNER JOIN departments ON schools.id=departments.school_id INNER JOIN
adoptions ON departments.id=adoptions.department_id
"UCA-2" "SPRING 2013" "ACCOUNTING" "ACCT" "3315" "COST ACCOUNTING" "10258" 10311
What I have is being generated with this code.
$row_array = array();
$terms = array();
$departments = array();
$courses = array();
$h = 0;
$i = 0;
$j = 0;
while ($row = mysqli_fetch_assoc($fetch)) {
$row_array[$row['school_name']]['school_name'] = $row['school_name'];
$akey = array_search($row['term_name'], $terms);
if ($akey === FALSE) {
$m = $h++;
$terms[] = $row['term_name'];
$row_array[$row['school_name']]['terms'][$m]['term_name'] = $row['term_name'];
} else {
$m = $akey;
}
$key = array_search($row['department_code'], $departments);
if ($key === FALSE) {
$k = $i++;
$departments[] = $row['department_code'];
$row_array[$row['school_name']]['terms'][$m]['departments'][$k]['department_name'] = $row['department_name'];
$row_array[$row['school_name']]['terms'][$m]['departments'][$k]['department_code'] = $row['department_code'];
} else {
$k = $key;
}
$skey = array_search($row['course_code'], $courses);
if ($skey === FALSE) {
$l = $j++;
$courses[] = $row['course_code'];
$row_array[$row['school_name']]['terms'][$m]['departments'][$k]['courses'][$l]['course_name'] = $row['course_name'];
$row_array[$row['school_name']]['terms'][$m]['departments'][$k]['courses'][$l]['course_code'] = $row['course_code'];
} else {
$l = $skey;
}
$row_array[$row['school_name']]['terms'][$m]['departments'][$k]['courses'][$l]['sections'][] = array('section_code' => $row['section_code'], 'unique_id' => $row['magento_course_id']);
}
How do I generate this JSON without those numbers showing up?
I think you have some key & encoding problems. Too much key usage, excessive loops in your code. Maybe you should tidy your sql query.
Since you are setting keys for courses, JSON shows it.
Try removing the key after "['courses']" in your last line such as;
Change ['courses'][$l] to ['courses'][]
At the end, encode the array for JSON.
$result = json_encode($result);

Categories