I'm trying to export the MySQL table below:
id, asof, value
abc, 2013-06-30, 36000000
abc, 2013-12-31, 48000000
abc, 2014-01-31, 51000000
abc, 2014-02-28, 56000000
xyz, 2013-06-30, 26000000
xyz, 2013-12-31, 33000000
xyz, 2014-01-31, 33000000
xyz, 2014-02-28, 36000000
into the following json format for use in the nvd3.js charts:
[
{
"key" : "abc" ,
"values" : [ [ 2013-06-30, 36000000] , [ 2013-12-31, 48000000] , [ 2014-01-31, 51000000] , [ 2014-02-28, 56000000]
},
{
"key" : "xyz" ,
"values" : [ [ 2013-06-30, 26000000] , [ 2013-12-31, 33000000] , [ 2014-01-31, 33000000] , [ 2014-02-28, 36000000]
}
]
I'm sure this is a newbie question but I'm struggling with it. Any guidance would be much appreciated!
Edit:
I've currently been trying to use an array and while statement but have not been able to figure out how to modify the array to so that it can output to the correct json format.
$query= mysqli_query($db,"SELECT id, asof, value
FROM table;"
);
if ( ! $query) {
echo mysqli_error();
die;
}
$rows = array();
while($r = mysqli_fetch_assoc($query)) {
$rows[] = $r;
}
print json_encode($rows);
Probably the most straightforward way of doing this is simply creating a multidimensional array, filling it with data obtained from database and then using json_encode to create a JSON string, which is then sent to the client.
Here is a simple example of a function which will accept an array of items and return a JSON string in the expected format. For simplicity, it is assumed that data was is a 2D array with three columns, but you should modify it to use the format returned by a database query.
function convert($data) {
$intermediate = array();
// This intermediate steps is used just to group all rows with
// the same key
foreach($data as $item) {
list($key, $date, $value) = $item;
$intermediate[$key][] = array($date, $value);
}
$output = array();
foreach($intermediate as $key => $values) {
$output[] = array(
'key' => $key,
'values' => $values
);
}
return $output;
}
Since you're getting data from database, variable $item inside the first foreach statement might actually be an associate array, so you'll have to write something like $item['key'] to get data for columns in the current row.
If you want to use mysqli_fetch_assoc, then you might try calling the function convert in the following way:
$conn = mysqli_connect('', '', '')
$query = 'SQL you wish to execute'
$result = mysqli_query($conn, $query)
if($result) {
$jsonData = convert($result);
}
However, function itself needs a little bit changing
function convert($result) {
$intermediate = array();
while($item = mysqli_fetch_assoc($result)) {
$key = $item['id'];
$date = $item['asof'];
$value = $item['value'];
$intermediate[$key][] = array($date, $value);
}
// The rest of the function stays the same
}
Related
Hi iam currently working on json based project.But iam having problem in encoding my data from my table like the below format.....I have seen a lot of json formats.....If any one can help me providing
php code snippet to encode exactly to such format.....
I need exactly such output where "data" is the array name
{
"data":[
{
"Id":1,
"Name":"Haben",
"Surname":"Dave",
"Age":22
},
{
"Id":12,
"Name":"Tomas",
"Surname":"Haleka",
"Age":32
},
{
"Id":123,
"Name":"Henok",
"Surname":"Dave",
"Age":28
},
{
"Id":1,
"Name":"Nafta",
"Surname":"Dave",
"Age":22
}
]
}
This will iterate through all selected rows and will encode them as Array. If you want to receive column names as they're in the table use below code.
$sql_query = "........";
$result = $db_connection->query($sql_query);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
print json_encode(array('data'=> $rows));
If you don't want to receive same column names as in database you can change how you want to receive them. You'll have to edit your while loop to do so.
while($r = mysqli_fetch_assoc($result)) {
$id = $r['user_id'];
$name = $r['user_name'];
$age = $r['user_age'];
$surname = $r['user_surname'];
$rows[] = array('Id' => $id, 'Name' => $name, 'Age' => $age, 'Surname' => $surname);
}
I am parsing thorugh a eBay API response. I want to deliver this back to a website cleaner and easier to parse with JavaScript. I successfuly Parsed through the XML... but now turning that into JSON to resend back to the client is giving me some headaches.
NOTE: $resp is the response from eBay. It's their full length XML that is successfully parsed with the code below.
For example... $valueName could be Grade. And then I go into the next foreach loop and get the values for this. These values may be 10, 9.5, 9 etc.
Here is my PHP code.
$arrayName = array();
$arrayValue = array();
foreach($resp->aspectHistogramContainer->aspect as $name) {
$nameAspect = $name['name'];
//$arrayName["aspectName"] = $nameAspect;
foreach($name->valueHistogram as $value) {
$valueAspect = $value['valueName'];
//$arrayValue["aspectValue"] = $valueAspect;
}
//array_push($arrayName, $arrayValue);
}
echo json_encode($arrayName);
So, without me trying to create my own JSON, I am getting that I need. I echos results and it was similar to this...
NAME
----- Value
----- Value
----- Value
NAME
----- Value
NAME
etc etc
For a JSON response... Im looking for something like...
[
{
"name": "NAME",
"value": ["value", "value"]
}, {
"name": "name",
"value": ["value", "value"]
}
]
Any help and guidance would be greatly appreciated.
eBay's response is like this (there are A LOT more <aspect> and <valueHistogram>)
<getHistogramsResponse xmlns="http://www.ebay.com/marketplace/search/v1/services">
<ack>Success</ack>
<version>1.13.0</version>
<timestamp>2018-11-07T15:32:20.380Z</timestamp>
<aspectHistogramContainer>
<domainDisplayName>Baseball Cards</domainDisplayName>
<aspect name="Card Manufacturer">
<valueHistogram valueName="Ace Authentic">
<count>19</count>
</valueHistogram>
<valueHistogram valueName="American Caramel">
<count>2024</count>
</valueHistogram>
<valueHistogram valueName="APBA">
<count>10554</count>
</valueHistogram>
<valueHistogram valueName="Bazooka">
<count>8826</count>
</valueHistogram>
<valueHistogram valueName="Be A Player">
<count>17</count>
</valueHistogram>
<valueHistogram valueName="Bell Brand Dodgers">
<count>334</count>
To encode it (and assuming SimpleXML), then it's just a case of building each internal $aspect data array and then adding the values to it. I use (string) to ensure the data is not stored as a SimpleXMLElement, which can cause side effects...
$arrayName = array();
foreach($resp->aspectHistogramContainer->aspect as $name) {
$aspect = [ "name" => (string)$name['name']];
foreach($name->valueHistogram as $value) {
$aspect["value"][] = (string)$value['valueName'];
}
$arrayName[] = $aspect;
}
echo json_encode($arrayName);
with the sample XML, this gives...
[{"name":"Card Manufacturer","value":["Ace Authentic","American Caramel","APBA","Bazooka","Be A Player","Bell Brand Dodgers"]}]
Create one single array $resultArray and store values in it. By maintaining your current code structure with minimal changes, here is the updated code snippet,
$resultArray = array();
$i = 0; // Maintain Array Index value
foreach($resp->aspectHistogramContainer->aspect as $name) {
$resultArray[$i]["aspectName"] = (string)$name['name'];;
foreach($name->valueHistogram as $value) {
$resultArray[$i]["aspectValue"][] = (string)$value['valueName'];
}
$i++; // Increment array index to store next value
}
echo json_encode($resultArray);
$results = array();
// Parse the XML into a keyed array
foreach($resp->aspectHistogramContainer->aspect as $name) {
$nameAspect = (string) $name['name'];
$values = array();
foreach($name->valueHistogram as $value) {
$values[] = (string) $value['valueName'];
}
$results[$nameAspect] = $values;
}
// This keeps things simple - rewrite to the required JSON format
$outputForJSON = array();
foreach ($results as $name => $values) {
$outputForJSON[] = array(
"name" => $name,
"values" => $values
);
}
echo json_encode($outputForJSON);
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
I'm trying to convert my array to JSON.
My JSON is stored in the database and will later be decoded for permission checking.
Example,
How I want it to be stored in the database:
{ "admin": 1,
"create_posts": 1,
"edit_posts": 1,
"delete_posts": 1 }
How it is being stored now:
{"0":"\"admin\": 1",
"1":"\"create_posts\": 1",
"2":"\"edit_posts\": 1",
"3":"\"delete_posts\": 1"}
My code:
$check_list = $_POST['check_list'];
$list = array();
foreach($check_list as $key) {
$key = '"' . $key .= '": 1';
array_push($list, $key);
}
$json = json_encode($list, JSON_FORCE_OBJECT);
How would I make it so that it stores in the database like I want it to be?
I'm quite new to this, so any hints instead of direct answers is also much appreciated!
UPDATE:
JSON decode and validation:
$permis = json_decode($permissions->permissions, true);
echo ($permis['admin'] == true) ? 'allowed' : 'disallowed';
$arr = [ 'a', 'b', 'c' ];
echo json_encode(
array_combine(
$arr,
array_fill(0, count($arr), 1)
),
JSON_PRETTY_PRINT
);
Output:
{
"a": 1,
"b": 1,
"c": 1
}
http://us3.php.net/manual/en/function.array-combine.php
http://us3.php.net/manual/en/function.array-fill.php
I'm assuming the incoming data looks like this.
$incoming_data = "admin=1&create_posts=1&edit_posts=1&delete_posts=1";
$pairs = parse_str($incoming_data);
so we take the incoming pairs and use the $key as the array index so you don't get the extra array element index.
$permissions = array();
foreach($pairs as $key => $value){
$permissions[$key] = $value;
}
then we encode the new array to get the JSON you're looking for.
print json_encode($permissions);
will print out JSON like this:
{
"admin":"1",
"create_posts":"1",
"edit_posts":"1",
"delete_posts":"1"
}
The main thing to change in your code is this.
foreach($check_list as $key) {
$list[$key] = 1;
}
I have inbound return data -> http://php.net/manual/en/function.json-decode.php that is in PhP array format. The file data is the same type. It is just $result from the previous cycle.
$result = api_query("mytrades", array("marketid" => $id));
How do I compare $result array with $file array and then over write FILE with $result data?
In other words, FILE and the data it contains is continuously being updated with $result
compare -> overwrite -> repeat at next execution.
I tried array_diff but it does not like my data types and I cannot find a work around.
Note: .db file is empty at first cycle but becomes populated at first write.
sample code with Array to string conversion error:
<?php
$id = 155;
require_once('phpPlay.php');
$result = api_query("mytrades", array("marketid" => $id));
$lines = file("myDB.db");
$arrayDiffresult = array_diff ( $result, $lines);
var_dump($result);
file_put_contents('myDB.db', print_r($result, true));
?>
var_dump($result);
I think, you looking for some serialization, json_encoding for example.
$result = array(
'return' => array(
array(
"tradeid" =>"74038377",
"tradetype" =>"Sell",
"datetime" =>"2014-11-12 16:05:32",
"tradeprice" =>"0.00675000",
"quantity" =>"22.18670000",
"fee" =>"-0.00007488",
"total" =>"0.14976023",
"initiate_ordertype" =>"Buy",
"order_id" =>"197009493",
),
array(
"tradeid" =>"2",
"tradetype" =>"Sell",
"datetime" =>"2014-11-12 16:05:32",
"tradeprice" =>"0.00675000",
"quantity" =>"22.18670000",
"fee" =>"-0.00007488",
"total" =>"0.14976023",
"initiate_ordertype" =>"Buy",
"order_id" =>"2",
)
)
);
function getdiff($new, $old)
{
//implement right logical diff here
$diff = array();
$old_serialized = array();
foreach ($old as $item) {
$old_serialized[] = json_encode($item);
}
foreach ($new as $item) {
if (in_array(json_encode($item), $old_serialized)) {
continue;
}
$diff[] = $item;
}
return $diff;
}
$old = file_exists('1.db') ? json_decode(file_get_contents('1.db'), 1) : array();
$arrayDiffresult = getdiff($result['return'], $old);
file_put_contents('1.db', json_encode($result['return']));
print_r($arrayDiffresult);