How to create json with objects as element from mysql multiple rows - php

Hi I pretty much stuck on creating json using php and mysql. I got lots of similar question and answers here but I cannot get what I want even after spending lots of time.I need my json output from mysql rows to be like
{ "application": [ { "ver": "1.0", "name": "myapp1" }, { "ver": "1.2", "name": "myapp2"}]}
I used following code for generating json,
$result=mysql_query("SELECT * FROM btrack_transaction");
$no_of_rows = mysql_num_rows($result);
$rows = array();
//retrieve and print every record
while($r = mysql_fetch_assoc($result)){
$rows[] = array('data' => $r);
}
// now all the rows have been fetched, it can be encoded
echo json_encode($rows);
But my output looks like
[[ { "ver": "1.0", "name": "myapp1" }, { "ver": "1.2", "name": "myapp2"}]]
How can I get the json format that I want .
Thanks in advance ,

while ($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode(array('application' => $rows));
You need to get rid of the extra array('data' => $r) wrapper around each element (I don't know why that doesn't show up in the output you say you get), and add the array('application' => $rows) at the end to add that element.

Related

Is it possible to Convert php database information to this format json file?

Is it possible to Convert php database information to this format json file??
About php Database Information
INSERT INTO `Peter` (`Name`, `Age`) VALUES ('Peter', '16');
Is it possible to json_encode to Convert php database information to the following format json file
Json File
[['Name','Peter'],['Age','16']]
NOT
[{
"Name": "Alberta",
"Age": "16"
}]
Thank you very much
Everything is possible. Since you are getting:
[{
"name": "Alberta",
"Age": "16"
}]
then I assume that you somehow load the data like this from your database (pseudocode):
$arrayOfResults = [];
while($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$arrayOfResults[] = $row;
}
or maybe more explicit:
$arrayOfResults = [];
while($row = $dbStatement->fetch(PDO::FETCH_ASSOC)) {
$arrayOfResults[] = [
'name' => $row['name'];
'Age' => $row['Age'];
];
}
Right?
Simply instead of adding the actual row add an array with db record's values where each element is an array itself:
$arrayOfResults = [];
while($row = $dbStatement->fetch(PDO::FETCH_ASSOC)) {
$arrayOfResults[] = [
[ 'Name', $row['name'] ],
[ 'Age', $row['age'] ]
];
}
Just a comment: generally if you want a format like that then you probably have something wrong in the code which is meant to read that file as you should not rely on on the order of elements in each row. In fact for your needs actually key => value format was established in the first place.

mysql result to multidimensional json array in different structure

I am struggling to achieve the correct json array format from the mysqli resultset. I have googled extensively and tried different things.
I am sql querying e-commerce orders and attempting to output them in JSON format to post to an application, in the JSON format specified by the application developer.
First tried this, outputs each line separately , not what I want:
while ( $row = $result->fetch_assoc()) {
$orders[]=$row;
}
echo json_encode($orders, JSON_PRETTY_PRINT);
The result was
[
{
"WebOrderNumber_C": "938276",
"itemName": "B3440S"
},
{
"WebOrderNumber_C": "938276",
"itemName": "D5035G"
},
{
"WebOrderNumber_C": "938276",
"itemName": "D6015"
}
]
Second having googled again and read other questions on here, I tried this
while ( $row = $result->fetch_assoc()) {
$orders[$row['WebOrderNumber_C']][] = $row['itemName'];
}
echo json_encode($orders, JSON_PRETTY_PRINT);
The result was
{
"938276": [
"B3440S",
"D5035G",
"D6015"
]
}
The format I am trying to achieve is this. please help
{
"WebOrderNumber_C": "938276",
"shipAddress": {
"add1": "LONDON"
},
"items": [{
"itemName": "B3440S"
},
{
"itemName": "B3440S"
},
{
"itemName": "B3440S"
}
]
}
PS I am Using PHP 5.6.30 if that is relevant.
Since the array you're adding to is nested, you need to create the parent object the first time you encounter a row with that order number. You can use an associative array for that, to make it easy to tell if the object already exists.
Then you add to the nested array, and wrap the item name in the associative array with the itemName key.
while ( $row = $result->fetch_assoc()) {
$orderno = $row['WebOrderNumber_C'];
if (!isset($orders[$orderno])) {
$orders[$orderno] = [
"WebOrderNumber_C" => $orderno,
"shipAddress" => [
"add1" => $row["add1"],
// other fields here ...
],
"items" => []
];
}
$orders[$orderno]["items"][] = ["itemName" => $row['itemName']];
}
$orders = array_values($orders); // Convert from associative array to indexed
echo json_encode($orders, JSON_PRETTY_PRINT);

PHP and JSON - extra comma in results

I'm trying to return json response in the correct format but I am getting an extra 'comma' in the returned code (comma after the last item 'Pencil'):
{
"results": [{
"ItemID": 1,
"ItemName": "Ball"
}, {
"ItemID": 2,
"ItemName": "Pen"
}, {
"ItemID": 3,
"ItemName": "Pencil"
},
}]
}
I tried different things but I can't get rid of it. Would anybody have any idea how to remove it?
The code that i have is this:
<?php
print '{"results":[';
for ($i=0; $i <$numrows; $i++) {
$stmt->fetch();
$JSONArray = array(
"ItemID" => $ItemID,
"ItemName" => $ItemName
);
print ",";
print json_encode($JSONArray);
}
print "]}"
?>
You're doing it ENTIRELY wrong. You're outputting multiple independent JSON strings, which is outright wrong. JSON is a monolithic "structure", and building it piece-wise is highly risky.
Simple: DOn't do that.
You build a standard PHP array, then do ONE SINGLE encoding when you're completely done building:
$arr = array();
for(...) {
$arr[] = ... add stuff ..
}
echo json_encode($arr);
First, fetching into bound variables is causing you an extra step, second, you don't need to construct any JSON. Just get all of your rows into the proper array structure and encode:
$result = $stmt->get_result();
while($rows['results'][] = $result->fetch_array(MYSQLI_ASSOC)){}
echo json_encode($rows);
If your system supports it, just use this instead of the while loop:
$rows['results'] = $result->fetch_all(MYSQLI_ASSOC);

PHP with JSON decode and steam api

I am new to php at this stage, same about openID libraries. I want to make a website for Steam users so I need to display their inventory. I've downloaded some example things which most thing written but I still need something else. As a training I took a something else than inventory, but similiar. Didn't make it so I hope that you can help me.
That's a example what I was looking at while trying to decode another data.
{
"response": {
"players": [
{
"steamid": "76hidden",
"communityvisibilitystate": 3,
"profilestate": 1
}
]
}
}
And code in PHP looks like
$url2 = file_get_contents("url");
$content = json_decode($url2, true);
$_SESSION['steam_steamid'] = $content['response']['players'][0]['steamid'];
$steamprofile['steamid'] = $_SESSION['steam_steamid'];
And this one above is working well. Could you please explain me why there is 0 between "steamid" and "players"? Also it looks like the session name matters, am I right? I was doing some tests and when I changed the name session it didn't work.
So here's what I am working on
JSON code:
{
"friendslist": {
"friends": [
{
"steamid": "765hidden",
"relationship": "friend",
"friend_since": 1428495026
},
{
"steamid": "764hidden",
"relationship": "friend",
"friend_since": 1355599210
},
{
"steamid": "764hidden",
"relationship": "friend",
"friend_since": 1423504205
},
much more friends
]
}
}
So I want to get the steamid and I got no idea how to get it. I've tried to get relationship as steamID is already used above:
$url3 = file_get_contents("url2");
$content2 = json_decode($url3, true);
$_SESSION['steam_relationship'] = $content2['friendslist']['friends'][0]['relationship'];
$steamfriends['friend'] = $_SESSION['steam_relationship'];
And of course echo $steamfriend['friend'] is not working. I see that person who made these PHP files already know what are the session names (if they need to be right to work). Any ideas where can I find it?
I feel really ashamed that I can't figure it myself.
Regards.
The first JSON
{
"response": {
"players": [
{
"communityvisibilitystate": 3,
"profilestate": 1,
"steamid": "76hidden"
}
]
}
}
translates to this PHP array
$content = array(
"response" => array(
"players" => array(
array(
"communityvisibilitystate" => 3,
"profilestate" => 1,
"steamid" => "76hidden"
)
)
)
)
The players is an array of arrays (hash arrays), so to access the first player you need to use index number ($content["response"]["players"][0]["steamid"]) even if there is just one player in the players array.
To get all steamids from the second array, you just need to run a simple foreach:
$friendIds = array();
foreach ($content2["friendslists"]["friends"] as $friend) {
$friendIds[] = $friend["steamid"];
}
# array("764hidden", "764hidden", "764hidden")
var_export($friendIds);
When the JSON is created they use a method similar to this:
foreach ($record as $response){
$content['response']['players'][] = $response;
}
Where $player may be an array with multiple values, or not.
It just makes it easier to create the JSON.
First make the JSON an array:
$array = json_decode($json,true)
Then get it like this:
session_start();
$_SESSION['relationship'] = $array['friendslist']['friends'][0]['relationship'];
$_SESSION['steamid'] = $array['friendslist']['friends'][0]['steamid'];
$_SESSION['steam_relationship'] = $array['friendslist']['friends'][0]['steam_relationship'];
The typical way to get all the player info:
foreach ($array['friendslist']['friends'] as $key => $value){
$steamid = $value['steamid'];
$relationship = $value['relationship'];
$friend_since = $value['friend_since'];
// do what need to be done here.
}

json_encode output in PHP not giving the data a label so it can be accessed

I am currently trying to pull existing data from my database to use on a page in real time,
I have a PHP file called json.php that use's the following code.
$sth = mysql_query("SELECT * FROM table ORDER BY id DESC");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
Which then outputs.
[
{
"id": "1",
"title": "1",
"img": "1.jpg"
},
{
"id": "2",
"title": "2",
"img": "2.png"
}
]
But as Im trying to learn online every example I see seems to have a label for each 'object' from the JSON then is called using something like,
json.label.title
How comes the PHP function doesn't print out a label so I can access the data in jQuery? Or have I done something wrong with my tables in MySQL?
As I said above I have tried researching online to learn how to do this but on every example I keep running into this problem.
Your JSON represents an array holding objects.
for (var i = 0; i < json.length; i++)
json[i].title; // your value
[...] is an array with numeric indexes (from 0 to array.length - 1) and {...} an object with string labels.

Categories