Create Json array from mysql data - php

I need a bit of help, i have this code:
$arr = [
"inventory_id" => 2937,
"products" => [],
];
$q = $dbc->query("SELECT quantity,productId FROM `Products` LIMIT 1");
while ($rs = $q->fetch_assoc()) {
$arr['products'][] = [$rs['productId'] => ["bl_3369" => $rs['quantity'] ] ];
}
which is returning
{
"inventory_id":2937,
"products":[
{
"154801353":{
"bl_3369":"10"
}
}
]
}
and i need to return like this:
{
"inventory_id": "2937",
"products": {
"154801353": {
"bl_3369": "10"
}
}
}
Could someone helping me? I search everywhere but i don't see how to adjust array to get needed structure

You're adding an extra array layer with the []. Change the code to this:
while ($rs = $q->fetch_assoc()) {
$arr['products'][$rs['productId']] = ["bl_3369" => $rs['quantity']];
}

Related

JSON format getting only one column

I am new to PHP so far I managed to get the following output from database in JSON format.I created an array result which returns workorderName, but I want to get workOrderId also in the same array so that I can use it in android string request.
{
"result": [
{
"$workOrderName": "electrician"
},
{
"$workOrderName": "plumber"
},
{
"$workOrderName": "carpenter"
}
]
}
my php code is
<?PHP
require_once('connection.php');
$workName = "SELECT work_order_id,workorder_name FROM workorder_category";
$con=mysqli_connect($server_name,$user_name,$password,$db);
$r = mysqli_query($con,$workName);
$result = array();
$resultArr = array('success' => true);
while($row = mysqli_fetch_array($r)){
array_push($result,array('$workOrderName'=>$row['workorder_name']));
}
echo json_encode(array('result'=>$result));
mysqli_close($con);
?>
I want the Output like
{
"result": [
{
"$workOrderId":"1"
"$workOrderName": "electrician"
},
{
"$workOrderId":"2"
"$workOrderName": "plumber"
},
{
"$workOrderId":"3"
"$workOrderName": "carpenter"
}
]
}
I'm pretty sure you didn't mean to have the $ in the key, but this is easier and will give you the column names (work_order_id, workorder_name) from the table as keys. Make sure to use mysqli_fetch_assoc:
while($row = mysqli_fetch_assoc($r)){
$result[] = $row;
}
If you want to change the keys then you can alias them in the query and use the above:
$workName = "SELECT work_order_id AS workOrderID, workorder_name AS workOrderName FROM workorder_category";
Or you could build the array:
$result[] = array('workOrderID' => $row['work_order_id'],
'workOrderName' => $row['workorder_name']);
You need to tweak your code to add $workOrderId also in the array like below
array_push($result,array(
'$workOrderId' => $row['work_order_id']
'$workOrderName' => $row['workorder_name']
));

PHP turn object into array of array

I have 3 tables, after joining name and output the role with this
$encoded = array();
while($res = mysqli_fetch_assoc($result)) {
echo json_encode($res);
}
I got this
{"student_id":"1","student_name":"john","score_id":"1","score_type":"E","score_name":"England"}
{"student_id":"1","student_name":"john","score_id":"2","score_type":"B","score_name":"Brazil"}
Now I'm struggling to turn them into the format I wanted, the client site have to have this
//json
[{
"student_id":"1",
"student_name":"john",
"scores": [{
"score_id":"1",
"score_type":"E",
"score_name":"England"
},{
"score_id":"2",
"score_type":"B",
"score_name":"Brazil"
}]
}]
The challenge is it has duplicated row with the same person.
Process the output using the Array $encoded and once it is built then you can print it with JSON.
In this solution the array will be indexed by student_id and the scores by score_id. In case of student it is a must, in case of scores it is recommended:
$encoded = array();
while($res = mysqli_fetch_assoc($result)) {
// Student's details
$encoded[$res['student_id']] = array(
'student_id' => $res['student_id'],
'student_name' => $res['student_name'],
);
// Student's score details
$encoded[$res['student_id']]['scores'][$res['score_id']] = array(
'score_id' => $res['score_id'],
'score_type' => $res['score_type'],
'score_name' => $res['score_name'],
);
}
echo json_encode($encoded);
Note: this is general answer since I do not know exact structure of your data in $res.
Please find the below code to get the json format as mentioned in your question
$students = [];
$sampleData = [
[
"student_id"=>"1",
"student_name"=>"john",
"score_id"=>"1",
"score_type"=>"E",
"score_name"=>"England",
],
[
"student_id"=>"1",
"student_name"=>"john",
"score_id"=>"2",
"score_type"=>"B",
"score_name"=>"Brazil",
],
];
foreach ($sampleData as $res) {
//if student not found by id then continue
if (empty($res['student_id'])) {
continue;
}
$student = [];
//get the already exists student to add scores
if(!empty($students[$res['student_id']])) {
$student = $students[$res['student_id']];
}
//prepare the student array
$student['student_id'] = $res['student_id'];
$student['student_name'] = $res['student_name'];
$student['scores'][]['score_id'] = $res['score_id'];
$student['scores'][]['score_type'] = $res['score_type'];
$student['scores'][]['score_name'] = $res['score_name'];
$students[$res['student_id']] = $student;
}
echo json_encode(array_values($students));
hope this helps
You can find the working example here

Need help constructing json with PHP

I want the following json data created with php.
I'am getting the required values from my database.
JSON i want to output(I created it manually to show):
{
"room":[
{
"id":"1",
"temp":"20"
},
{
"id":"2",
"temp":"30"
}
]
}
Current PHP:
$rows = array();
if(!$allData->count()) {
echo 'No results!';
} else {
foreach ($allData->results() as $allData) {
$rows['id'] = $allData->id;
$rows['data'] = $allData->temp;
}
}
// echo out as json data
echo '{"rom":'.json_encode($rows).'}';
This is what my current PHP script outputs:
{"rom":{"id":"2","data":"20"}}
JSON formatted:
{
"rom":{
"id":"2",
"temp":"30"
}
}
As you can see it outputs only the last id and temp values..
I can't seem to find out what I'am doing wrong, any help is greatly appreciated.
You are missing one dimension in your array:
$rows = array();
if(!$allData->count()) {
echo 'No results!';
} else {
foreach ($allData->results() as $allData) {
$rows[] = [
'id' => $allData->id,
'data' => $allData->temp,
];
}
}
Consider this:
$rows[] = ["id"=>$allData->id, "data"=>$allData->temp];
I n this way you never overwrite previous data

Why I can't format my JSON object?

I'm trying to construct a json object containing inner objects.
I'm trying the following code - where $ids is an array containing some IDs:
$result = array();
foreach ($ids as $value) {
$tempArray = getCustomOptions($host, $dbUsername, $dbPassword, $dbName, $_SESSION['companyId'], $value);
array_push($result, $tempArray);
}
print_r(json_encode($result));
The getCustomOptions() also returns an array using the following script:
$dataArray = [];
while ($stmt->fetch()) {
$dataArray[] = array(
'id' => $id,
'description' => $description
);
}
The problem is that when I print_r(json_encode($result)); I'm getting the following result:
[
[
{
"id":21,
"description":"Bshd"
},
{
"id":22,
"description":"Gandhi "
},
{
"id":23,
"description":"aaaa"
},
{
"id":24,
"description":"bbbbb"
}
],
[
{
"id":12,
"description":"121"
},
{
"id":13,
"description":"qwe"
},
{
"id":16,
"description":"wD2"
},
{
"id":17,
"description":"we"
}
],
[
]
]
As you can see it returns some arrays inside of an array, but what I really need is the following structure:
{
"data1":[
{
"id":21,
"description":"Bshd"
},
{
"id":22,
"description":"Gandhi "
},
{
"id":23,
"description":"aaaa"
},
{
"id":24,
"description":"bbbbb"
}
],
"data2":[
{
"id":12,
"description":"121"
},
{
"id":13,
"description":"qwe"
},
{
"id":16,
"description":"wD2"
},
{
"id":17,
"description":"we"
}
]
}
I know that I'm missing something really small and basic here, but for me the JSON manipulation in php is still hard.
Can somebody give me a clue or a push?
you can try following code to generate your array in a proper format.
$result = array();
$i=1;
foreach ($ids as $value) {
$tempArray = getCustomOptions($host, $dbUsername, $dbPassword, $dbName, $_SESSION['companyId'], $value);
$result['data'.$i] = $tempArray;
$i++;
}
Don't use array_push() that just creates a normal array element. Use $array_variable[$key] = ... to assign values to a specific associative array key.

create custom json array from database result in php?

Hi I have some table say fro example table1 ,table2 in my mysql databse.
I need to get following json result from php.
Can anyone suggest how to achieve this?
any good tutorial doing same is also helpful.
I am able to convert database result in simple json response but custom response is something difficult for me.
{
response:ok
tables:[
{
name:table name
data:[
{
fieldname1:value1
fieldname2:values2
},
{
fieldname1:value1
fieldname2:value2
}
.
.
]
},
{
name:table name1
data:[
{
fieldname1:value1
fieldname2:values2
},
{
fieldname1:value1
fieldname2:value2
}
.
.
]
},
]
}
}
Quoting from How to convert mysql data base table data in json using php, once you have your table names you can do for each of them.
$result = array();
$result['response'] = 'ok'
foreach ($tables as $tableName) {
$query = mysql_query("SELECT * FROM $tableName");
$rows = array();
while($row = mysql_fetch_assoc($query)) {
$rows[] = $row;
}
$result['tables'][] = array(
'name' = $tableName,
'data' = $rows
)
}
print json_encode($result);

Categories