mysql result to multidimensional json array in different structure - php

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);

Related

How to search through nested JSON arrays in PHP

I'm sorry if I don't use the correct terminology, I'm still learning. I'm trying to figure out how to search a JSON array that has nested arrays in it for a specific value, and then return an associated value.
My problem is similar to this answered question on StackOverflow (How to search through a JSON Array in PHP), but I want to be able to find an item by id in either people or dog or any other nested array. Essentially I want to convert people below in the foreach to a wildcard.
Here is my JSON data - http://foothillertech.com/student/webdesign/2018/2018benrud2/tinker/dataIntro2/test/data.json
foreach($json->people as $item)
{
if($item->id == "8097")
{
echo $item->content;
}
}
Any help is greatly appreciated.
If id is unique in the data, you can merge the inner arrays and index them by id.
$data = json_decode($json, true);
$merged = array_merge(...array_values($data));
$indexed = array_column($merged, null, 'id');
Then you can look up any of the items by id.
echo $indexed['8097']['content'] ?? 'not found';
This only works if id is unique. If not, indexing by id will result in data loss.
In this case, simply do two loops.
$json = json_decode('{
"people": [
{
"id": "8080",
"content": "foo"
},
{
"id": "8097",
"content": "bar"
}
],
"dogs": [
{
"id": "8081",
"content": "spot"
},
{
"id": "8091",
"content": "max"
}
]
}');
foreach($json as $key=>$value){
//$key = people or dogs
//$value = stdClass()
foreach($value as $item)
{
if($item->id == "8097")
{
echo $item->content;
}
}
}
Output
bar
Sandbox
If we used 8081 instead of 8097 I would expect to get 'spot`. And testing that, I do indeed get that (which is in dogs).

JSON object with array header

this question comes from the posting I found here:
DataTables Multiple Tables from Multiple JSON Arrays
I'd like to know the simplest and best way to generate the JSON below. I can see the pattern is 'JSON object -> Array Header -> Array -> JSON object' but I do not know how to do this in PHP, from a mySQLi query result. I imagine having a mySQL table with a 'policies' and 'services' column so the query might look something like:
Select name, id, score, type from myTable where type = 'policies' and
type = 'services'
And the result would come back something like:
name id score type
A 1 0 policies
B 2 0 services
But then how would I take that query and generate this JSON in php?
{
"Policies": [
{
"name": "A",
"id": "1",
"score": "0"
}
],
"Services": [
{
"name": "B",
"id": "2",
"score": "0"
}
]
}
Thanks for your help!
Start by creating the new empty array.
Then, iterate through the result and add it in the correct sub-array:
$new = [];
foreach ($result as $item) {
// Uppercase the first character
$type = ucfirst($item['type']);
if (!isset($new[$type])) {
// This type doesn't exist in the new array yet, let's create it.
$new[$type] = [];
}
// Add the item
$new[$type][] = $item;
}
// Output it as json
echo json_encode($new, JSON_PRETTY_PRINT);
The above code will also work if new types are added to the database.
PS. The JSON_PRETTY_PRINT argument is just to make the json string a bit more readable while developing. When everything looks good, you can remove it.

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.
}

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

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.

Categories