How to split and change the json format - php

I am using slimphp v2 and I have the following function
function gt($user) {
$sql = "select id, id as categoryId, mobile, task from actions where status=0";
try {
$db = newDB($user);
$stmt = $db - > prepare($sql);
$stmt - > execute();
$gs = $stmt - > fetchAll(PDO::FETCH_OBJ);
if ($gs) {
$db = null;
echo json_encode($gs, JSON_UNESCAPED_UNICODE);
} else {
echo "Not Found";
}
} catch (PDOException $e) {
echo '{"error":{"text":'.$e - > getMessage().
'}}';
}
}
The default json output looks like:
[{
"id": "1",
"categoryId": "1",
"mobile": "111",
"task": "test"
},
{
"id": "2",
"categoryId": "2",
"mobile": "222",
"task": "test2"
}]
and the output that i am trying to make. I need to generate an ID: 1_(id) then format it like this
[{
id: "1",
task: "test",
}, {
ID: "1_1", //generate this, add 1_id
categoryId: "1",
mobile: "00000",
}, {
id: "2",
task: "test2",
}, {
ID: "1_2", //generate this, add 1_id
categoryId: "2",
mobile: "11111"
}];
Is it possible?
Thanks

I'm not sure if this is exactly what your after but you can gain the desired JSON output by converting your original JSON into an associative array and then restructure the data on each iteration using a Foreach() loop into a new assoc array. After that, you can just convert it back to JSON using json_encode().
Code:
$json = '[{
"id": "1",
"categoryId": "1",
"mobile": "111",
"task": "test"
},
{
"id": "2",
"categoryId": "2",
"mobile": "222",
"task": "test2"
}]';
$jsonArr = json_decode($json, TRUE);
$newArr = [];
foreach ($jsonArr as $v) {
$newArr[] = ['id:'=>$v['id'], 'task:' => $v['task']];
$newArr[] = ['ID:'=>'1_' . $v['id'], 'categoryId' => $v['categoryId'], 'mobile'=>$v['mobile']];
}
$newJson = json_encode($newArr);
var_dump($newJson);
Output:
[{
"id:": "1",
"task:": "test"
}, {
"ID:": "1_1",
"categoryId": "1",
"mobile": "111"
}, {
"id:": "2",
"task:": "test2"
}, {
"ID:": "1_2",
"categoryId": "2",
"mobile": "222"
}]
Edit -- Updated Answer
As discussed in comments, your outputting your SQL array as an object. I've set the Fetch to output as an associative array using PDO::FETCH_ASSOC and changed the foreach() loop to reference the assoc array $gs. This should work but if not then output your results for $gs again using var_dump($gs). You will still need to encode to JSON if needed but this line has been commented out.
function gt($user) {
$sql = "select id, id as categoryId, mobile, task from actions where status=0";
try {
$db = newDB($user);
$stmt = $db->prepare($sql);
$stmt->execute();
$gs = $stmt->fetchAll(PDO::FETCH_ASSOC); //Fetch as Associative Array
if ($gs) {
$db = null;
$newArr = [];
foreach ($gs as $v) { //$gs Array should still work with foreach loop
$newArr[] = ['id:'=>$v['id'], 'task:' => $v['task']];
$newArr[] = ['ID:'=>'1_' . $v['id'], 'categoryId' => $v['categoryId'], 'mobile'=>$v['mobile']];
}
//$newJson = json_encode($newArr); //JSON encode here if you want it converted to JSON.
} else {
echo "Not Found";
}
} catch(PDOException $e) {
//error_log($e->getMessage(), 3, '/var/tmp/php.log');
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}

Related

nested JSON array to csv in PHP

How can I output this json to csv properly?
My json file pattern is like this:
{
"swimmers": [
{
"Province": "Ontario",
"Exemption": "S9,SB9,SM9",
"Code": "A,3,4",
"Level": "Level 8",
"ClassificationDate": "2020",
"RYEar": "2024",
"Status": "Registered",
"ID": "123456",
"FirstName": "John",
"LastName": "Doe",
"Gender": "M",
"AGE": null,
"DOB": "01/11/2000",
"Clubs": [
{
"Clubname": "Human Fish",
"Code": "ABC",
"Clubid": "300"
}
],
"Email": null,
"Language": "E",
"ChallengeData": null
}
//more entries with same pattern as first
],
"status": "OK",
"application": "SOme App API"
}
I had success to turn it into a csv with the code below but I'm unable to output the clubs field in the csv file, instead of showing the club, it just shows "Array()". I tried to fix that with the commented code but it doesn't solve the problem.
$csvFileName = 'converted.csv';
$json = 'myjson.json';
$data = file_get_contents($json);
$payload= json_decode($data);
$file_pointer = fopen($csvFileName, 'w');
if ($file_pointer){
foreach($payload['swimmers'] as $row) {
// $clubs = $row['Clubs'] ;
// if (is_array($clubs)){
// foreach($clubs as $c){
// fputcsv($file_pointer, $c);
// }
// }else{
fputcsv($file_pointer, $row);
}
}
Append each element of the Clubs field to $row, then remove the Clubs field.
foreach ($payload['swimmers'] as $row) {
foreach ($row['Clubs'] as $club) {
$row = array_merge($row, array_values($club));
}
unset($row['Clubs']);
fputcsv($file_pointer, $row);
}

Export database to json in a specific format

When Exporting database to json I get it in this form:
[
{
"id": "1",
"siteId": "1",
"siteUrl": "localhost",
"identity": "mobie",
"lastIp": "127.0.0.1",
"lastLogin": "2018-05-17",
"loginCountry": "GB",
}
]
Warning: Illegal string offset 'id' in C:\xamppp\htdocs\auth\mysql.php on line 81
To all of the $user variables.
My database structure is shown as above in the first json output.
Code
public function db2json($query){
$stmt = $this->db->prepare($query);
$stmt->execute();
$data=$stmt->fetch(PDO::FETCH_ASSOC);
$output = [];
foreach ( $data as $result ) { // Change this to loop over the data
$user = [];
$user["id"] = $result["id"];
$user["siteId"] = $result["siteId"];
$user["lastIp"] = $result["lastIp"];
$user["lastLogin"] = $result["lastLogin"];
$user["loginCountry"] = $result["loginCountry"];
$output[$result["siteUrl"]][$result["identity"]] = $user;
}
echo json_encode($output, JSON_PRETTY_PRINT);
}
I have had to build up some test data, but this will just mean that you change the foreach() to loop over your database result instead. Rather than just assigning the result straight to the output, this just creates the various arrays as you want them in the output...
$output = [];
foreach ( $data as $result ) { // Change this to loop over the data
$user = [];
$user["id"] = $result["id"];
$user["siteId"] = $result["siteId"];
$user["lastIp"] = $result["lastIp"];
$user["lastLogin"] = $result["lastLogin"];
$user["loginCountry"] = $result["loginCountry"];
$output[$result["siteUrl"]][$result["identity"]] = $user;
}
echo json_encode($output, JSON_PRETTY_PRINT);
With my test data, this outputs...
{
"localhost": {
"mobie": {
"id": "1",
"siteId": "1",
"lastIp": "127.0.0.1",
"lastLogin": "2018-05-17",
"loginCountry": "GB"
},
"user2": {
"id": "1",
"siteId": "1",
"lastIp": "127.0.0.1",
"lastLogin": "2018-05-17",
"loginCountry": "GB"
}
},
"othersite": {
"user1": {
"id": "1",
"siteId": "1",
"lastIp": "127.0.0.1",
"lastLogin": "2018-05-17",
"loginCountry": "GB"
}
}
}

merging two arrays in php from mysql and converting to json

I have two arrays which i want to merge and map the values together where it's id's are same . The problem is when i use array_merge function it only merges two arrays and resulting json is does not fit my model in android.
Here is php function :-
public function getfromorders(){
$sql = 'SELECT * FROM p_orders';
$query = $this -> conn -> prepare($sql);
$query -> execute(array());
$pro1=array();
$orders =array();
while($data = $query -> fetch(PDO::FETCH_OBJ))
{
$orders[] = $data;
$pro1[] = $data -> p_id;
}
$pro=array();
foreach ($pro1 as $id0) {
$sql = 'SELECT * FROM products WHERE p_id = :p_id';
$query2 = $this -> conn -> prepare($sql);
$query2 -> execute(array(':p_id' => $id0));
while($products = $query2 -> fetch(PDO::FETCH_OBJ))
{
$pro[] = $products;
}
}
return array_merge($pro,$orders);
}
Here is resulting json :-
{
"products": [
{
"p_id": "4",
"p_name": "Data Structures and algorithm in C++",
"p_info": "Adam Drozdek",
"p_sold": "Book Available : 20",
"p_image": "http://www.buildupcareer.com/gauti/Hunt/Food.jpg",
"p_type": "Veg",
"p_star": "0"
},
{
"p_id": "12",
"p_name": " Kadai Paneer",
"p_info": "An Indian vegetarian dish made with cottage cheese cooked with tomatoes-onions-bell peppers- and a blend of Indian spices",
"p_sold": "Spicy",
"p_image": "http://www.buildupcareer.com/gauti/Hunt/Burger.jpg",
"p_type": "Start-ups",
"p_star": "0"
},
{
"email": "7827789246",
"p_id": "4",
"noi": "1",
"order_id": "36"
},
{
"email": "7827789246",
"p_id": "12",
"noi": "1",
"order_id": "35"
}
],
"result": "success"
}
I want that resulting json should merge the (p_id,email,noi ,order_id) with the (p_id,p_name,p_info......) without changing the mysql database . Is there a way to achieve this?
Here is my expected json:-
{
"products": [
{
"p_id": "4",
"p_name": "Data Structures and algorithm in C++",
"p_info": "Adam Drozdek",
"p_sold": "Book Available : 20",
"p_image": "http://www.buildupcareer.com/gauti/Hunt/Food.jpg",
"p_type": "Veg",
"p_star": "0",
"email": "7827789246",
"noi": "1",
"order_id": "36"
},
{
"p_id": "12",
"p_name": " Kadai Paneer",
"p_info": "An Indian vegetarian dish made with cottage cheese cooked with tomatoes-onions-bell peppers- and a blend of Indian spices",
"p_sold": "Spicy",
"p_image": "http://www.buildupcareer.com/gauti/Hunt/Burger.jpg",
"p_type": "Start-ups",
"p_star": "0",
"email": "7827789246",
"p_id": "12",
"noi": "1",
"order_id": "35"
}
],
"result": "success"
}
This is how you can construct your JSON:
while($products = $query2 -> fetch(PDO::FETCH_OBJ)) {
$newElement = array();
foreach($products as $key => value) {
if ($key !== "p_id") {
$newElement[$key] = $value;
}
}
if (!isset($pro[$products["p_id"]])) {
$pro["p_id"] = array();
}
$pro["p_id"][]=$newElement;
}
Note that to avoid duplicating p_id, I have used it as a key. Each key is associated with an array of items.

Json Parsing error using JSON.parse()

I have developed an api which will post some data in json format to be used in an android app. However I am getting json parsing error. I am new to this whole json thing so unable to understand what the error means.
This is my json encoded output that the php backend generates
{
"data": [
{
"id": "2",
"name": "Rice",
"price": "120",
"description": "Plain Rice",
"image": "6990_abstract-photo-2.jpg",
"time": "12 mins",
"catagory": "Lunch",
"subcat": ""
}
]
}{
"data": [
{
"id": "4",
"name": "Dal",
"price": "5",
"description": "dadadad",
"image": "",
"time": "20 mins",
"catagory": "Dinner",
"subcat": ""
}
]
}{
"data": [
"catagory": "Soup"
]
}
This is the error the online json parser gives
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 2 column 1 of the JSON data
What is actually wrong here? Could you please provide me with the correct json output for the following data?
This should clear it up
$main = array();
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$cat = $row['category'];
$query1 = "SELECT * FROM item WHERE catagory='$cat'"; //Prepare login query
$value = $DBH->query($query1);
if($row1 = $value->fetch(PDO::FETCH_OBJ))
{
$main[] = array('data'=>array($row1));
}
else
{
$main[] = array('data'=>array('catagory'=>$row['category']));
}
}
echo json_encode($main);
You shouldn't create your json string by hand. Create your array structure, then finally invoke json_encode() at the end.
$data = array();
try
{
$query = "SELECT category FROM category"; // select category FROM category? what?
$result= $DBH->query($query);
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$cat = $row['category'];
$query1 = "SELECT * FROM item WHERE catagory='$cat'";
$value = $DBH->query($query1);
if($value->rowCount() > 0) {
$data[] = array('data' => $value->fetch(PDO::FETCH_ASSOC));
}
else {
$sub = array('category' => $row['category']);
$data[] = array('data' => $sub);
}
}
$result->closeCursor();
$DBH = null;
echo json_encode($data); // encode at the end
}
catch(PDOException $e)
{
print $e->getMessage ();
die();
}

PHP Array to JSON

I'm trying to build a JSON object from a mysql query. The JSON structure that I'm striving for should look like this:
{
"a": [
{
"user": "alb",
"time": "2011-09-12 05:56:36"
},
{
"user": "arg",
"time": "2011-09-12 05:56:36"
}
]
"b": [
{
"user": "blah",
"time": "2011-09-12 05:56:36"
},
{
"user": "bleh",
"time": "2011-09-12 05:56:36"
}
]
}
However, my code always returns a JSON object wrapped in an array like so:
[
{
"a": [
{
"user": "alb",
"time": "2011-09-12 05:56:36"
},
{
"user": "arg",
"time": "2011-09-12 05:56:36"
}
]
"b": [
{
"user": "blah",
"time": "2011-09-12 05:56:36"
},
{
"user": "bleh",
"time": "2011-09-12 05:56:36"
}
]
}
]
Here is the php code I'm using:
<?php
$json_data = array();
foreach($blogs as $blog)
{
$sql = "SELECT * from users";
$query = mysql_query($sql);
$ablog = array();
while ($row = mysql_fetch_assoc($query))
{
$json_element = array(
"user"=> $row[username] ,
"time"=> $row[time]
);
array_push($ablog,$json_element);
}
$eblog = array($blog => $ablog);
array_push($json_data,$eblog);
}
$json_output = json_encode($json_data);
print $json_output;
?>
I was wondering: Why am I getting a JSON object wrapped in an array? What am I doing incorrectly in the code above?
Thank you.
The following two lines are creating one-element associative arrays and appending the one-element array to your larger $json_data array:
$eblog = array($blog => $ablog);
array_push($json_data,$eblog);
Instead, just add a new key/value pair to your original array:
$json_data[$blog] = $ablog;

Categories