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;
Related
I have this json code
"result": [
{
"update_id": 74783732,
"message": {
"message_id": 852,
"from": {
"id": ---,
"is_bot": false,
"first_name": "---",
"username": "---",
"language_code": "en"
},
"chat": {
"id": ---,
"first_name": "---",
"username": "---",
"type": "private"
},
"date": 1646306224,
"text": "#username",
"entities": [
{
"offset": 0,
"length": 16,
"type": "mention"
}
]
}
}
]
I can get content from update_id , message, first_name etc.
but I want to get "mention" from type how can i do it?
my code is
here i decode json and get arrays from json and put them in variable and use it in my queries but I cant get mention from entities...
$update = file_get_contents("php://input");
$update_array = json_decode($update, true);
if( isset($update_array["message"]) )
{
$text = $update_array["message"]["text"];
$chat_id = $update_array["message"]["chat"]["id"];
}
if(isset($update_array["message"]["entities"]["type"]) and $update_array=="mention")
{
$get_username = $text;
show_users_by_username($get_username);
}
tnx for helping
$update_array will never be equal to "mention" but $update_array["message"]["entities"]["type"] yes.
Change your condition.
I am trying to parse a xml to a nested json structure with php.
This is my test script:
$json_drives = array();
foreach($drives->DR as $dr){
$current_drive = array();
$current_drive['id'] = $dr->ID;
$current_drive['name'] = $dr->NAME->D;
$json_drives[] = $current_drive;
}
echo("Finished");
// Parse and save
$f = json_encode($json_drives);
file_put_contents('test12345.json', $f);
I get a structure like that:
[
{
"id": {
"0": "1"
},
"name": {
"0": "Name 1"
}
},
{
"id": {
"0": "2"
},
"name": {
"0": "Name 2"
}
},
// ...
]
But I dont want the keys "id" and "name" to be nested. It should look like this:
[
{
"id": "1"
"name": "Name 1"
},
{
"id": "2"
"name": "Name 2"
},
// ...
]
How can I handle that?
Assuming your JSON's "drive" objects will always have this structure:
"id": {
"0": "Some ID"
},
"name": {
"0": "Some name"
}
You can use:
$current_drive['id'] = ((array) $dr->ID)[0];
$current_drive['name'] = ((array) $dr->NAME->D)[0];
Hi i am trying to merge output of MySQL result in JSON format but i confused how i can do this so guys i need your helps please tell me how i can do this work thank you.
SQL:
$result = $db->sql_query("SELECT a.*,i.member_id,i.members_seo_name
FROM ".TBL_IPB_USER." i
LEFT JOIN ".TBL_IPB_LA." a
ON a.member_id=i.member_id
WHERE i.".$column." = '".$val."' AND a.game = '".$game."'");
while( $dbarray = $db->sql_fetchrow($result) ){
$arr[] = $dbarray;
}
return ($arr);
The normal result and output with JSON format for my query is:
{
"status": 200,
"result": [
{
"member_id": "1",
"member_name": "maxdom",
"ip_address": "177.68.246.162",
"session_onlineplay": "1",
"sid": "IR63374a32d1424b9288c5f2a5ce161d",
"xuid": "0110000100000001",
"serialnumber": "9923806a06b7f700a6ef607099cb71c6",
"game": "PlusMW3",
"members_seo_name": "maxdom"
},
{
"member_id": "1",
"member_name": "maxdom",
"ip_address": "81.254.186.210",
"session_onlineplay": "1",
"sid": "IR3cd62da2f143e7b5c8f652d32ed314",
"xuid": "0110000100000001",
"serialnumber": "978e2b2668ec26e77c40c760f89c7b31",
"game": "PlusMW3",
"members_seo_name": "maxdom"
}
],
"handle": "checkUSER"
}
But i want to merge output and result like this one:
{
"status": 200,
"result": [
{
"member_id": "1",
"member_name": "maxdom",
"ip_address": [
"177.68.246.162",
"81.254.186.210"
],
"session_onlineplay": "1",
"sid": [
"IR63374a32d1424b9288c5f2a5ce161d",
"IR3cd62da2f143e7b5c8f652d32ed314"
],
"xuid": "0110000100000001",
"serialnumber": [
"9923806a06b7f700a6ef607099cb71c6",
"978e2b2668ec26e77c40c760f89c7b31"
],
"game": "PlusMW3",
"members_seo_name": "maxdom"
}
],
"handle": "checkUSER"
}
you better use php for your parser, prevent high load for database, this is sample code
$result = $db->sql_query("SELECT a.*,i.member_id,i.members_seo_name
FROM ".TBL_IPB_USER." i
LEFT JOIN ".TBL_IPB_LA." a
ON a.member_id=i.member_id
WHERE i.".$column." = '".$val."' AND a.game = '".$game."'");
$arr = array();
while( $dbarray = $db->sql_fetchrow($result) ){
$item = $dbarray;
$item['ip_address'] = array($item['ip_address']);
$item['sid'] = array($item['sid']);
$item['serialnumber'] = array($item['serialnumber']);
$index = $dbarray['member_id'];
if(isset($arr[$index]))
{
$arr[$index]['ip_address'] = array_merge($arr[$index]['ip_address'], $item['ip_address'];
$arr[$index]['sid'] = array_merge($arr[$index]['sid'], $item['sid'];
$arr[$index]['serialnumber'] = array_merge($arr[$index]['serialnumber'], $item['serialnumber']);
} else {
$arr[$index] = $item;
}
}
return array_values($arr);
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() .'}}';
}
}
this is my php code, to obtain json format data
if($status==1)
{
$post_id=$json_object['post_id'];
$get_postid=mysqli_query($con,"select * from User_Post where post_id='$post_id'");
if(mysqli_num_rows($get_postid)==0)
{
//For failure status if session id is wrong.
http_response_code(500);
echo json_encode(array("error_code"=>"500","error_message"=>"Sorry, post id does not exists."));
}
else
{
foreach($field_check as $values)
{
if($values=='id')
{
$row_array = array();
while ($row = $get_postid->fetch_array())
{
$row_array['id']=$row['post_id'];
$row_array['image_urls']=explode(',',$row['post_image_url']);
$storetag= explode(',',$row['Post_tagged_id']);
$has_liked="false";
$has_commented="false";
}
}
elseif($values=='tagged_users')
{
while ($row = $get_postid->fetch_array())
{
$storetag= explode(',',$row['Post_tagged_id']);
$has_liked="false";
$has_commented="false";
}
for($i=0;$i<count($storetag);$i++)
{
$user=mysqli_query($con,"select user_id, profile_image_url from Wheel_User where user_id='$storetag[$i]'");
if(mysqli_num_rows($user)==0)
{
//For failure status if session id is wrong.
http_response_code(500);
echo json_encode(array("error_code"=>"500","error_message"=>"Sorry, post id does not exists.".die()));
}
else
{
while ($row = $user->fetch_array())
{
$tagged_users[$i]['user_id']=$row['user_id'];
$array['user_id']=$tagged_users[$i]['user_id'];
$pro_image_url[$i]=$row['profile_image_url'];
$short_image_url[$i]=str_replace('_b','_t',$pro_image_url[$i]);
$short_image_url[$i]=str_replace('/images/','/thumbnails/',$short_image_url[$i]);
$array['short_image_url']=$short_image_url[$i];
}
}
array_push($row_array,$array);
}
}
}
array_push($json_response,$row_array);
echo str_replace('\/','/',json_encode($json_response));
}
}
It is returning the following objects
[
{
"id": "1111",
"image_urls": [
"https://docs.google.com/document/d/14kVqw9d2kzYIEClN-SVp2Co2mlglM9F-8HIy0ggTZ3g/edit",
"http://stackoverflow.com/questions/21762150/how-do-i-insert-data-from-a-json-array-into-mysql-database",
"https://drive.google.com/?authuser=0#my-drive",
"https://drive.google.com/?tab=mo&authuser=0#shared-with-me"
],
"0": {
"user_id": "111",
"short_image_url": "chrome://restclient/content/thumbnails/restclient_t.jpg"
},
"1": {
"user_id": "321",
"short_image_url": "chrome://restclient/thumbnails/restclient_t.jpg"
},
"2": {
"user_id": "1234",
"short_image_url": "http://54.169.40.195/wheel/wheel/service/testing/chetan/audio/c71dfe45421b2864476a0bde257f0a57e72084783ce859e26595599670904907.mp3"
}
}
]
but i want to assign name to that array like this
[
{
"id": "1111",
"image_urls": [
"https://docs.google.com/document/d/14kVqw9d2kzYIEClN-SVp2Co2mlglM9F-8HIy0ggTZ3g/edit",
"http://stackoverflow.com/questions/21762150/how-do-i-insert-data-from-a-json-array-into-mysql-database",
"https://drive.google.com/?authuser=0#my-drive",
"https://drive.google.com/?tab=mo&authuser=0#shared-with-me"
],
"tagged_users":[
"0": {
"user_id": "111",
"short_image_url": "chrome://restclient/content/thumbnails/restclient_t.jpg"
},
"1": {
"user_id": "321",
"short_image_url": "chrome://restclient/thumbnails/restclient_t.jpg"
},
"2": {
"user_id": "1234",
"short_image_url": "http://54.169.40.195/wheel/wheel/service/testing/chetan/audio/c71dfe45421b2864476a0bde257f0a57e72084783ce859e26595599670904907.mp3"
}
]
}
i don't know where i have to add this array name. Please help me solve this.
I can't assign the array name like this because $row_array also contains other data
echo str_replace('\/','/',json_encode(array("tagged_user"=>$json_response));
On second to last line this should be what you wanted:
array_push($json_response,array("tagged_users" => $row_array));
Edited to remove second part.
Try with -
array_push($row_array['tagged_users'],$array);
Or define it like -
$row_array['tagged_users'] = array();
Then all the values will be as you want.