I need to convert the below result. I generate this JSON array using PHP but now I need the same result into a single curly brace. Below is my PHP code to generate the JSON.
$arr = array();
#If no data was returned, check for any SQL errors
if ($res == false)
{
echo 'Query not Executed : '. die(print_r(sqlsrv_errors(), TRUE));
}
else
{
while($obj = sqlsrv_fetch_array($res, SQLSRV_FETCH_ASSOC))
{
$arr[] = array(
'code' => array_search($obj['name'], $countries_iso),
'total' => $obj['Total']
);
}
}
header("Content-type: application/json");
#Output the JSON data
print (json_encode($arr));
Output of above PHP code:
[
{
code: "AF",
total: 1
},
{
code: "DZ",
total: 1
},
{
code: "AS",
total: 2
}
]
But I want to show like below result:
{
"AF":1
"DZ": 1,
"AS": 2
}
I guess you want $arr[array_search($obj['name'], $countries_iso)] = $obj['Total'];
Your mistake was the fact that you were declaring a new array each time you add something to your original array. This way you assign the correct way :)
Try this code:
$arr = array();
#If no data was returned, check for any SQL errors
if ($res == false)
{
echo 'Query not Executed : '. die(print_r(sqlsrv_errors(), TRUE));
}
else
{
while($obj = sqlsrv_fetch_array($res, SQLSRV_FETCH_ASSOC))
{
$arr[array_search($obj['name'], $countries_iso)] = $obj['Total'];
}
}
header("Content-type: application/json");
#Output the JSON data
//$json = json_encode($arr);
$json = json_encode($arr);
Just do this:
$arr[array_search($obj['name'], $countries_iso)] = $obj['Total'];
But you can get rid of the whole array_search($obj['name'], $countries_iso) if you restrict the query to only return rows WHERE name IN (list of $countries_iso). Look up WHERE and IN for SQL Server.
You need to transform your data structure to an associative array, where the value you are currently storing in code will be the key and the value stored in total will be value.
I'll be able to help better if you post the code that generates your current JSON object
Related
php code:
<?php
$mysqli = new mysqli("localhost","root","root","thinkorders"); //Database connection start
$sql = "select * from psv_post"; //fetch table data
$result = $mysqli->query($sql); //process query
$json_response = array(); //main array
$shipping_address_details = array();
$items_details = array();
while($row=$result->fetch_array(MYSQLI_BOTH))
{
//main array
$json_response['contact_id'] = $row['contact_id'];
//shipping_address details array
$shipping_address_details['country'] = $row['shipping_address_country'];
//items_details array
$items_details['type'] = $row['items_type'];
//push shipping address into shipping_address details array
$json_response['shipping_address'][] = $shipping_address_details;
//push items into items_details array
$json_response['items'][] = $items_details;
}
header('Content-type: text/javascript');
//echo json_encode($json_response);
$json_output = json_encode($json_response); //OUTPUT
//remove square braces from json string
$json_output = str_replace('[','',$json_output);
echo $json_output = str_replace(']','',$json_output);
?>
this code returns:
{
"contact_id": "625",
"shipping_address": {
"country": "USA"
},
"items": {
"type": "paper"
}
}
i need it like this:
{
"contact_id": "625",
"shipping_address": {
"country": "USA"
},
"items": [
{
"type": "paper"
}
]
}
After searching for a couple of hours it seems that its an array inside an object (see the square brackets), but everything i try has not worked. If someone can see an easy fix, please reply. Thank you!
Remove this part of code
//remove square braces from json string
$json_output = str_replace('[','',$json_output);
echo $json_output = str_replace(']','',$json_output);
After I removed the code that kalloz recommended, all I had to do is remove the "[]" from my push string:
//push shipping address into shipping_address details array
$json_response['shipping_address'] = $shipping_address_details;
and of course edit the new last line to add "echo":
echo $json_output = json_encode($json_response); //OUTPUT
Based on your question details, your answer, and your comment, I believe I understand your coding intent and I would like to offer a logical rewrite so that your process is a bit more direct and readable.
Untested Code: (resultset to array demo)
header('Content-type: application/json');
if (!$mysqli = new mysqli("localhost", "root", "root", "thinkorders")) {
$response = 'Connection Error'; // $mysqli->connect_error;
} else {
$sql = "SELECT contact_id,
shipping_address_country,
GROUP_CONCAT(items_type)
FROM psv_post
WHERE contact_id = 625
GROUP BY contact_id";
if (!$result = $mysqli->query($sql)) {
$response = 'Syntax Error'; // $mysqli->error
} elseif (!$row = $mysqli->fetch_assoc()) {
$response = 'Possible Logic Error - No Rows Found';
} else {
$response = [
'contact_id' => $row['contact_id'],
'shipping_address' => ['country' => $row['shipping_address_country']],
'items' => array_map(function($v) {return ['type' => $v];}, explode(',', $row['items_type']))
];
}
}
echo json_encode($response);
If you have no control over the construction of your json string, never use string functions to modify (hack at) a json string. Rather, you should decode it, modify the elements/objects/etc then re-encode when you are done. Of course, if you DO have control of the construction, then try to correct the array before encoding.
A header() declaration is probably not necessary, but if you want/need it then use application/json.
Build in some error reporting to make debugging simple.
Instead of iterating and overwriting column values that never change, use GROUP_ calls in your query. This will set up the resultset processing so that only a single column (which may have multiple values) will be iterated.
No matter what happens in your process, always echo a json string.
p.s. your snippet is written in a way that suggests you will only target one contact_id's data. If this is true, I wonder how that id is being determined. If the targeting id is being passed in (via GET/POST or other untrustworthy means) then you should cast the value as an integer or use a prepared statement with a placeholder and a bound parameter for security reasons.
I'm writing a PHP code for inserting the work order name in a spinner.
I need a JSON String called success = 1 along with JSON Array.
I want to use that JSON string in the android spinner.
I'm getting only JSON array.
here is my code:
<?PHP
require_once('connection.php');
$workName = "SELECT 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 an output as like this:
{"success":1,result":[{"$workOrderName":"electrician"},{"$workOrderName":"plumber"},{"$workOrderName":"carpenter"}]}
currently, I am getting the output like
{
"result": [
{
"$workOrderName": "electrician"
},
{
"$workOrderName": "plumber"
},
{
"$workOrderName": "carpenter"
}
]
}
Instead of creating two arrays, one for the result and one for the success, define the structure in just one array and append to that:
// The main structure
$result = [
'success' => 1,
'result' => [],
];
while($row = mysqli_fetch_array($r)){
// Append to the sub key "result" (which we already defined as an array)
$result['result'][] = ['$workOrderName'=>$row['workorder_name']];
}
// Just encode the complete array
echo json_encode($result);
Note: This example uses the short array syntax [] (introduced in PHP 5.4) instead of the long syntax: array(). They do the exact same thing.
I also changed array_push() to a shorter version: $someArray[] =.
$result = array();
$resultArr['success'] =true;
while($row = mysqli_fetch_array($r))
{
array_push($result,array('$workOrderName'=>$row['workorder_name']));
}
$resultArr['result'] = $result;
echo json_encode($resultArr);
This will work fine.
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']
));
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
I need to edit some data in a JSON file, and I'm looking to do so in PHP. My JSON file looks like this:
[
{
"field1":"data1-1",
"field2":"data1-2"
},
{
"field1":"data2-1",
"field2":"data2-2"
}
]
What I've done so far is $data = json_decode(file_get_contents(foo.json)) but I have no idea how to navigate this array. If for example I want to find the data from the first field of the second object, what's the PHP syntax to do so? Also, are there other ways I should know about for parsing JSON data into a PHP friendly format?
This JSON contains 2 arrays with 2 objects each, you can access like this:
$arr = json_decode(file_get_contents(foo.json));
// first array
echo $arr[0]->field1;
echo $arr[0]->field2;
// second array
echo $arr[1]->field1;
echo $arr[1]->field2;
if you convert this to an array and avoid objects you can then access like this:
$arr = json_decode(file_get_contents(foo.json), true);
// first array
echo $arr[0]['field1'];
echo $arr[0]['field2'];
// second array
echo $arr[1]['field1'];
echo $arr[1]['field2'];
$data = json_decode(file_get_contents(foo.json));
foreach($data as $k => &$obj) {
$obj->field1 = 'new-data1-1';
$obj->field2 = 'new-data1-2';
}
Please use this code to navigate through your json format. This code is dynamic and can navigate for any number of objects you have in your result.
<?php
$json ='[
{
"field1":"data1-1",
"field2":"data1-2"
},
{
"field1":"data2-1",
"field2":"data2-2"
}
]';
if($encoded=json_decode($json,true))
{
echo 'encoded';
// loop through the json values
foreach($encoded as $key=>$value)
{
echo'<br>object index: '.$key.'<br>';
foreach($value as $bKey=>$bValue)
{
echo '<br> '.$bValue.' = '.$bValue;
}
}
// get a perticular item
echo '<br>object[0][field1]: '.$encoded[0]['field1'];
}
else
{
echo'error on syntax';
}
?>
Which will have following output
encoded
object index: 0
data1-1 = data1-1
data1-2 = data1-2
object index: 1
data2-1 = data2-1
data2-2 = data2-2
object[0][field1]: data1-1