Two queries mysql in one object json - php

I have two tables that I want to convert them to json like this:
[
{
"date":"2013-07-20",
"id":"123456",
"year":"2013",
"people":[
{
"name":"First",
"age":"60",
"city":"1"
},
{
"name":"second",
"age":"40",
"city":"2"
},
{
"name":"third",
"age":"36",
"city":"1"
}
]
}
]
but the result of my code is this:
[
{
"date":"2013-07-20",
"id":"123456",
"year":"2013",}
,{
"people":[
{
"name":"First",
"age":"60",
"city":"1"
},
{
"name":"second",
"age":"40",
"city":"2"
},
{
"name":"third",
"age":"36",
"city":"1"
}
]
}
]
the code creates a new object to the array "people" and I want that are in the same object
$result = mysql_query("SELECT * FROM data where id='123456'");
$fetch = mysql_query("SELECT name,age,city FROM people where id='123456'");
$json = array();
$json2['people'] = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$json[] = $row;
}
while ($row = mysql_fetch_assoc($fetch)){
$row_temp["name"]=$row["name"];
$row_temp["age"] = $row["age"];
$row_temp["city"] = $row["city"];
array_push($json2['people'],$row_temp);
}
array_push($json, $json2);
echo Json_encode($json);
How I can make the array is in the same object as the table "data"?
Many thanks

I think you may try this
$result = mysql_query("SELECT * FROM data where id='123456'");
$fetch = mysql_query("SELECT name,age,city FROM people where id='123456'");
// I think, you'll get a single row, so no need to loop
$json = mysql_fetch_array($result, MYSQL_ASSOC);
$json2 = array();
while ($row = mysql_fetch_assoc($fetch)){
$json2[] = array(
'name' => $row["name"],
'age' => $row["age"],
'city' => $row["city"]
);
}
$json['people'] = $json2;
echo json_encode($json);
Result of print_r($json) should be something like this
Array
(
[date] => 2013-07-20
[year] => 2013
[id] => 123456
[people] => Array
(
[0] => Array
(
[name] => First
[age] => 60
[city] => 1
)
[1] => Array
(
[name] => second
[age] => 40
[city] => 2
)
)
)
Result of echo json_encode($json) should be
{
"date" : "2013-07-20",
"year":"2013",
"id":"123456",
"people":
[
{
"name" : "First",
"age" : "60",
"city" : "1"
},
{
"name" : "second",
"age" : "40",
"city" : "2"
}
]
}
If you do echo json_encode(array($json)) then you will get your whole json wrapped in an array, something like this
[
{
"date" : "2013-07-20",
"year":"2013",
"id":"123456",
"people":
[
{
"name" : "First",
"age" : "60",
"city" : "1"
},
{
"name" : "second",
"age" : "40",
"city" : "2"
}
]
}
]

You were very close, but you want the People array to be a direct value of the outer array and you've wrapped it in an extra array.
Also, please note that the MySQL library you are using is deprecated. That means it will be removed from PHP in a future release. You should replace calls from the MySQL_* family of functions with either mysqli or pdo
$result = mysql_query("SELECT * FROM data where id='123456'");
$fetch = mysql_query("SELECT name,age,city FROM people where id='123456'");
$json = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$json[] = $row;
}
$json['people'] = array();
while ($row = mysql_fetch_assoc($fetch)){
$row_temp["name"]=$row["name"];
$row_temp["age"] = $row["age"];
$row_temp["city"] = $row["city"];
array_push($json['people'],$row_temp);
}
echo Json_encode($json);

You can make it work by waiting to use the key people until the very end when you join the two arrays. Up until then, just load the data into $json and $json2.
$json = array('date' => '2013', 'id' => '123456', 'year' => '2013');
$result = mysql_query("SELECT * FROM data where id='123456'");
$fetch = mysql_query("SELECT name,age,city FROM people where id='123456'");
$json = array();
$json2 = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$json[] = $row;
}
while ($row = mysql_fetch_assoc($fetch)){
$row_temp["name"]=$row["name"];
$row_temp["age"] = $row["age"];
$row_temp["city"] = $row["city"];
array_push($json2, $row_temp);
}
$json['people'] = $json2;
echo Json_encode($json);

Related

PHP ordering json array format

Im trying to get a json array, from a sql database which needs to be in the above format
{
"data":[
{
"name": "foo",
"age":"bar"
},
{
"name": "hello",
"age":"hi"
},
{
"name": "bar",
"age":"foo"
},
]
}
My code below return the data like,
{
"0": [
"name" : "blah",
"age" : "bleh"
],
"1": [
"name": "bleh",
"age" : "blah"
],
"data": []
}
CODE
$_SESSION['userID'] = $userID;
include('USERconfig.php');
$dataArray = array("data"=>array());
$sql = "SELECT name, age FROM dataQue";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
array_push($dataArray,
array("name"=>$row['name'],"age"=>$row['age']));
}
sqlsrv_free_stmt( $stmt);
header('Content-Type: application/json');
echo json_encode($dataArray);
exit();
How can i get all the data to be appended within the 'data' array?
And how can i get rid of the "0","1","2" ect.. ?
thanks in advance!
array_push() will insert data into the array after what you already have in it, I suggest you change the way you insert data in it by just calling back the array in the loop like this
$i = 0;
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$dataArray['data'][$i]['name'] = $row['name'];
$dataArray['data'][$i]['age'] = $row['age'];
$i++;
}
this way all data retrieved from your query will be added to date index. By adding index ($i) will avoid replacing previous register.
You can use :
json_decode($dataArray);
add TRUE to json_decode like :
$dataArray = '{"data":[{"name": "foo","age":"bar"},
{"name": "hello","age":"hi"},
{"name": "bar","age":"foo"}]}';
print_r(json_decode($dataArray, true));
the result will be:
Array(
[data] => Array
(
[0] => Array
(
[name] => foo
[age] => bar
)
[1] => Array
(
[name] => hello
[age] => hi
)
[2] => Array
(
[name] => bar
[age] => foo
)
))

Mapping SQL query results to JSON in PHP

I'm running into some issues getting the correct JSON output from my SQL query. Essentially what I'm struggling with is getting an array of options objects as opposed to singular option objects.
$query = 'SELECT matchup.matchupID, matchup_option.player_name, matchup_option.player_id FROM matchup
INNER JOIN matchup_option
ON matchup_option.matchupID= matchup.matchupID;';
$attachments = $db->query($query);
$data = array();
while ($attachment = $db->fetch_array($attachments)){
$data[] = array (
'id' => $attachment['matchupID'],
'options' => array(
array (
"name" => $attachment['player_name'],
"playerid" => $attachment['player_id']
)
)
);
//VAR_DUMP($attachment);
}
$data = array("matchup"=>$data);
print json_encode($data);
Gives me this output:
{
"matchup":[
{
"id":"111222",
"options":[
{
"name":"111",
"playerid":"111"
}
]
},
{
"id":"111222",
"options":[
{
"name":"222",
"playerid":"222"
}
]
}
]
}
And here's what I'm trying to get to:
{
"matchup":[
{
"id":"111222",
"options":[
{
"name":"111",
"playerid":"111"
},
{
"name":"222",
"playerid":"222"
}
]
}
]
}
I'd like to follow best practices as well as structure this appropriately, if there's a better way to go about this, please let me know!
You need to store $attachment['matchupID'] as an array key of $data:
$data = array();
while ($attachment = $db->fetch_array($attachments)){
if (!isset($data[$attachment['matchupID']])) {
$data[$attachment['matchupID']] = array (
'id' => $attachment['matchupID'],
'options' => array()
);
}
$data[$attachment['matchupID']]['options'][] = array (
"name" => $attachment['player_name'],
"playerid" => $attachment['player_id']
);
}
// use `array_values` to reindex `$data`
$data = array("matchup" => array_values($data));
print json_encode($data);

create style of JSON object with PHP

my JSON currently looks like this
{
"customers":
[
{
"customer_id":3,
"customer_name":"Rick",
"Address":"333 North Road"
},
{
"customer_id":4,
"customer_name":"Robby",
"Address":"444 North West Road"
}
]
}
and I would like it to look like this
{
"customers":
[
{
"customer":
{
"customer_id":3,
"customer_name":"Rick",
"Address":"333 North Road"
}
},
{
"customer":
{
"customer_id":4,
"customer_name":"Robby",
"Address":"444 North West Road"
}
}
]
}
It is being created in this php script but I'm unsure how to add the customer attribute to each JSON object programmtically. help please?
//populate results
$json = array();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$array = array(
'customer_id' => $row['CustomerID'],
'customer_name' => $row['Name'],
'Address' => $row['Address']
);
array_push($json, $array);
foreach ($row as $r) {
}
}
$jsonstring = '{"customers":'. json_encode($json). "}";
return $jsonstring;
//populate results
$json = array();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$array = array("customer" => array( // <-- change is here
'customer_id' => $row['CustomerID'],
'customer_name' => $row['Name'],
'Address' => $row['Address']
)
);
array_push($json, $array);
foreach ($row as $r) {
}
}
$jsonstring = '{"customers":'. json_encode($json). "}";
return $jsonstring;

PHP - foreach function with array

Hi I have an error when I call a function.
"Warning: Illegal string offset 'id' in C:\xampp\htdocs\blog\posts.php
on line 28
2"
function:
function get_short_posts() {
$sql = "SELECT * FROM posts ORDER by id DESC LIMIT 0, 5";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
$timestamp = new DateTime($row['date']);
return array (
"id" => $row['id'],
"title" => $row['title'],
"content" => $row['content'],
"author" => $row['author'],
"date" => $timestamp->format('d-m-Y'),
"time" => $timestamp->format('H:i')
);
}
Call:
require_once "functions.php";
$_posts = get_short_posts();
foreach($_posts as $_post) {
echo $_post['id'];
}
You know you return after the first iteration in the get_short_posts function right, so the foreach will not work as expected.
Try:
<?php
function get_short_posts() {
$sql = "SELECT * FROM posts ORDER by id DESC LIMIT 0, 5";
$result = mysql_query($sql);
$return = array();
while($row = mysql_fetch_assoc($result)) {
$timestamp = new DateTime($row['date']);
$return[] = array (
"id" => $row['id'],
"title" => $row['title'],
"content" => $row['content'],
"author" => $row['author'],
"date" => $timestamp->format('d-m-Y'),
"time" => $timestamp->format('H:i')
);
}
return $return;
}
?>
<?php
require_once "functions.php";
foreach(get_short_posts() as $_post) {
echo $_post['id'];
}
?>
Also, Don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
function get_short_posts() {
$sql = "SELECT * FROM posts ORDER by id DESC LIMIT 0, 5";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
$timestamp = new DateTime($row['date']);
$data [] = array (
"id" => $row['id'],
"title" => $row['title'],
"content" => $row['content'],
"author" => $row['author'],
"date" => $timestamp->format('d-m-Y'),
"time" => $timestamp->format('H:i')
);
}
return $data;
}
you return data, so the loop stops, save your data in a array and return that array like abive code
Your code is wrong it should be as below, assuming the query is returning data as mentioned.
function get_short_posts() {
$sql = "SELECT * FROM posts ORDER by id DESC LIMIT 0, 5";
$result = mysql_query($sql);
$rows = array();
$return_data = array();
while($row = mysql_fetch_assoc($result)) {
$timestamp = new DateTime($row['date']);
$data = array (
"id" => $row['id'],
"title" => $row['title'],
"content" => $row['content'],
"author" => $row['author'],
"date" => $timestamp->format('d-m-Y'),
"time" => $timestamp->format('H:i')
);
$return_data[] = $data;
}
return $return_data ;
}
require_once "functions.php";
$posts = get_short_posts();
foreach($posts as $key=>$val) {
echo $val['id'];
}

php json_decode with data wrapped by [ ]

with true option, it works fine.
sorry and thanks guys.
=============================================
I encoded php array to json with this code
$rows = array();
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
echo json_encode($rows);
/* free result set */
$result->free();
}
end decode with
$array = json_decode($server_output)
the $server_output is like this
[{"userid":"96679","userinfor":"xxxxxxxxx","userlocation":"CA"}]
[{"userid":"153795","userinfor":"xxxxxxxxx","userlocation":"CA"}]
[{"userid":"131878","userinfor":"xxxxxxxxx","userlocation":"CA"}]
but, $array is NULL :(
Thanks in advence,
This is not valid json together:
[{"userid":"96679","userinfor":"xxxxxxxxx","userlocation":"CA"}]
[{"userid":"153795","userinfor":"xxxxxxxxx","userlocation":"CA"}]
[{"userid":"131878","userinfor":"xxxxxxxxx","userlocation":"CA"}]
While, this part is valid:
[{"userid":"96679","userinfor":"xxxxxxxxx","userlocation":"CA"}]
or any one of them separately
$json = '[{"userid":"96679","userinfor":"xxxxxxxxx","userlocation":"CA"}]';
print_r(json_decode($json, true));
Output:
Array
(
[0] => Array
(
[userid] => 96679
[userinfor] => xxxxxxxxx
[userlocation] => CA
)
)
The valid format for all data is like this:
[
{
"userid": "96679",
"userinfor": "xxxxxxxxx",
"userlocation": "CA"
},
{
"userid": "153795",
"userinfor": "xxxxxxxxx",
"userlocation": "CA"
},
{
"userid": "131878",
"userinfor": "xxxxxxxxx",
"userlocation": "CA"
}
]

Categories