JSON object with array header - php

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.

Related

PHP - Deleting an element of a JSON array changes the array syntax

I can successfully delete elements of a JSON array with PHP, but I cannot understand why the JSON array changes syntax after deleting an element that's not the last one.
So, here's my User.json file:
[
{
"id": "kS79BhPx"
},
{
"id": "ycC7km7A"
},
{
"id": "hgF5D4es"
}
]
Here's my delete.php script:
$className = "Users";
// get the index
$index = (int)$_GET['index'];
//fetch data from json
$data = file_get_contents($className. '.json');
$data_array = json_decode($data, true);
// delete the row with the index
unset($data_array[$index]);
//encode back to json
$data = json_encode($data_array, JSON_PRETTY_PRINT);
file_put_contents($className. '.json', $data);
So, if I go to the following URL, just to test my php function:
https://example.com/delete.php?index=0
The script successfully deletes the first element of the JSON array, but then it changes into this:
{
"1": {
"id": "ycC7km7A"
},
"2": {
"id": "hgF5D4es"
}
}
Instead, if I set https://example.com/delete.php?index=2 - so I want to delete the last array's element - it saves it as follows:
[
{
"id": "kS79BhPx"
},
{
"id": "ycC7km7A"
}
]
This last result is what I need to achieve all the times I delete an element because I need the JSON array syntax to stay as [...], not as {...}.
What am I doing wrong in my PHP script?
Using unset() on an array (associative or not) in PHP will preserve the existing keys making the array associative. You need to reindex the array after using unset():
// delete the row with the index
unset($data_array[$index]);
$data_array = array_values($data_array);

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

Create array from row objects in the same table :: PHP + SQL

I have an array like so
id | userID | item
1 ! 1 | {"property": 0, "property": "string"}
2 ! 1 | {"property": 4, "property": "string2"}
and I wish to return one array with like so:
[{
"property": 0,
"property": "string"
},
{
"property": 4,
"property": "string2"
}]
No matter what I try I cannot seem to get it to work properly. Either I get a whole string so number values get converted, or I get an object with \" everywhere. Currently I have this code
if ($query = $mysqli->query("SELECT item FROM userItems WHERE userID = 'id' "))
{
while ($row = $query->fetch_object())
{
$result->items[count($result)] = $row;
}
}
$test = stripslashes(json_encode($result->items));
which returns this ...
{"1":{"item":"{"property":"0","property":"string"}"}}
Been trying to solve it for hours and can't get it right
I tried your code and there're two main things:
you're building an array of associative arrays but associative array tends to overwrite identical associative keys with the latter in your code - in your case both keys are property,
the data you're retrieving from DB (userItems.item) already seems to be JSON encoded so you need to call json_decode() somewhere instead of calling json_encode() again; decoding your $row->item ($result->items[count($result)] = json_decode($row->item);) seems to do the trick.
Just as a sidenote you should consider wrapping your id parameter in SQL query into mysqli_real_escape_string() or so.
Let me know if that helped and you see the desired result now.

How to create a JSON array in php?

I am trying to create a simple android application that takes data from a database and displays it in a list format on the android screen. I made a php script that queries the database and returns a json object. I convert the json object into json array and extract the relevant data for display. But I am getting this error "JSONException: type org.json.JSONObject cannot be converted to JSONArray".
Following is my php script -
// response Array
$response = array("tag" => $tag, "success" => 0, "error" => 0);
$username = $_POST['username'];
$events = $db->viewAttendingEvent($username);
if ($events) {
$response["success"] = 1;
$response["event"]["owner"] = $events["owner"];
$response["event"]["friendsnames"] = $events["friendsnames"];
$response["event"]["vote"] = $events["vote"];
$response["event"]["accepted"] = $events["accepted"];
$response["event"]["eventname"] = $events["eventname"];
$response["event"]["eventnumber"] = $events["eventnumber"];
$response["event"]["created_at"] = $events["created_at"];
echo json_encode($response);
This is the json which I receive back :
{
"tag": "view_invitations",
"success": 1,
"error": 0,
"event": {
"owner": "jkkkkoopp",
"friendsnames": "don",
"vote": "0",
"accepted": "f",
"eventname": "yyy",
"eventnumber": "11",
"created_at": "2014-05-29 22:27:31.843528"
}
}
I am trying to extract 'event' from this json object, which is not an array.
it should be
{
"event": [
{
"owner": "jkkkkoopp",
"friendsnames": "don",
"vote": "0",
"accepted": "f",
"eventname": "yyy",
"eventnumber": "11",
"created_at": "2014-05-2922: 27: 31.843528"
}
]
}
Can someone help me how to make this a valid jsonArray ? Thanks
If you're looking to get a JavaScript 'Array' (from which I mean an Object with nothing but integer keys) then you need to only have integer keys in your PHP Array.
This article is a pretty good resource and explains some of the differences between arrays and objects in javascript. The relevant quote here comes from the What Arrays Are section (emphasis mine):
Javascript arrays are a type of object used for storing multiple
values in a single variable. Each value gets numeric index and may be
any data type.
No it should not be what you proposed it should be. If that were the case you would have to have your php be this:
$response["event"][0]["owner"] = $events["owner"];
$response["event"][0]["friendsnames"] = $events["friendsnames"];
$response["event"][0]["vote"] = $events["vote"];
$response["event"][0]["accepted"] = $events["accepted"];
$response["event"][0]["eventname"] = $events["eventname"];
$response["event"][0]["eventnumber"] = $events["eventnumber"];
$response["event"][0]["created_at"] = $events["created_at"];
The way you have it now is event is an associative array so it converts it to an object. You are expecting that event = an array of objects. So you need to either change your php code to make event be an array of objects (as demonstrated above) or you need to modify your expectations to have event = an object.

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