I'd encoded my result into json and I want to merge them. I wish to achieve this
[
{
"post_id": 1,
"content": "test image feature",
"date": "0000-00-00",
"category_id": 1,
"lp_title": "",
"lp_image": "",
"lp_canonicalUrl": "",
"lp_url": "",
"lp_desc": "",
"lp_iframe": "",
"lp_iframe_id": ""
"img_src" [{img_src:1.jpg},{img_src:2.jpg}]
}
]
http://pastebin.com/7jKp9BUn
the result of each statement
[
{
"img_src": "1.jpg"
},
{
"img_src": "2.jpg"
}
]
the next one
[
{
"post_id": 1,
"content": "test image feature",
"date": "0000-00-00",
"category_id": 1,
"lp_title": "",
"lp_image": "",
"lp_canonicalUrl": "",
"lp_url": "",
"lp_desc": "",
"lp_iframe": "",
"lp_iframe_id": ""
}
]
You can decode the JSON into arrays, append one to the other, then re-encode:
$s1 = '[
{
"img_src": "1.jpg"
},
{
"img_src": "2.jpg"
}
]';
$s2 = '[
{
"post_id": 1,
"content": "test image feature",
"date": "0000-00-00",
"category_id": 1,
"lp_title": "",
"lp_image": "",
"lp_canonicalUrl": "",
"lp_url": "",
"lp_desc": "",
"lp_iframe": "",
"lp_iframe_id": ""
}
]';
//decode each
$arr1 = json_decode($s1, true);
$arr2 = json_decode($s2, true);
$arr2[0]['img_src'] = $arr1;
//re-encode as a JSON string and show output
$sf = json_encode($arr2);
echo $sf;
This should give the result you described, with "img_src"... as a sub-array of the larger set.
Looking at your php code you could do it this way as well in one shot.
$stmt = $db->prepare("
SELECT post_id,content,date,category_id,lp_title,lp_image,lp_canonicalUrl,lp_url,lp_desc,lp_iframe,lp_iframe_id
FROM post_items inner JOIN user ON post_items.user_id = user.user_id
WHERE post_items.user_id = ? order by post_items.post_id desc LIMIT ?,?");
$stmt->bind_param('iii', $userid, $itemStart, $itemEnd);
$stmt2 = $db->prepare("SELECT photo_upload.img_src FROM photo_upload inner JOIN post_items ON post_items.photo_set_id = photo_upload.photo_set_id
WHERE post_items.photo_set_id = photo_upload.photo_set_id ");
//store the images in a separate array
$imgArray = array();
if ($stmt2->execute()) {
$photo_items = $stmt2->get_result();
while ($obj2 = $photo_items->fetch_object()) {
$imgArray[] = $obj2;
}
}
if($stmt->execute()){
$post_items = $stmt->get_result();
if(mysqli_num_rows($post_items) > 0){
while ($obj = $post_items->fetch_object()) {
$jsonData[] = $obj;
// check if there are any elements in the array
if(count($imgArray) > 0){
// set the img_src index of the jsonData array with the elements of the other array
$jsonData['img_src'] = $imgArray;
}
}
$i = json_encode($jsonData);
echo $i;
}
}
Related
i have many to many relationship
like this :
Server version: 10.4.17-MariaDB
table colors(id,name).
table items(id,title....).
table item_color(id,items_id,color_id).
my query is like this :
SELECT items.*,colors.name FROM items,item_color,colors
where
items.id = item_color.item_id
and
colors.id = item_color.color_id
i use php function json_encode().
how to return this :
{
"id": "22",
"title": "my products 515151",
"descreption": "5454545455",
"price": "0.05",
"quantity": "2",
"date_added": "2021-01-29 14:37:24",
"primary_image": "http://localhost/ecomerce/uploads/1611927444hat.jpg",
"color": [
0 : "pink",
1 : "white"
]
}
instead if this:
"id": "22",
"title": "my products 515151",
"descreption": "5454545455",
"price": "0.05",
"quantity": "2",
"date_added": "2021-01-29 14:37:24",
"primary_image": "http://localhost/ecomerce/uploads/1611927444hat.jpg",
"color": "pink"
},
{
"id": "22",
"title": "my products 515151",
"descreption": "5454545455",
"price": "0.05",
"quantity": "2",
"date_added": "2021-01-29 14:37:24",
"primary_image": "http://localhost/ecomerce/uploads/1611927444hat.jpg",
"color": "red"
},
There's 2 way to do it:
If you want to keep your query, you must parse the data first before you parse it to json.
...
function regroup_color($data = array()){
$ret = array();
foreach($data as $d){
$id = $d['id'];
if(!isset($ret[$id])){
$color = $d['color'];
unset($d['color']);
$ret[$id] = $d;
$ret[$id]['color'][] = $color;
}else{
$ret[$id]['color'][] = $d['color'];
}
}
return $ret;
}
$data = regroup_color($data);
echo json_encode($data)
...
Or you could just...
make the query 2 part, first is for get all items, second is for get the colors for it
...
$query = "SELECT * FROM items";
// get the data here using query above
$data = {{result of query}};
foreach($data as $i => $d){
$id = $d['id'];
$query = "SELECT * FROM item_color JOIN colors ON item_color.color_id = colors.id";
// get the data here using query above
$colors = {{result of query}};
foreach($colors as color){
$data[$i]['color'][] = $color['name'];
}
}
echo json_encode($data)
...
i wanted to add also category so this is what i came with
function regroup_color($data = array(),$data2 = array()){
// array that will hold our data and we will return it later
$ret = array();
// fetch the data as d
foreach($data as $d){
//save the id
$id = $d['id'];
//make sure no id was set
if(!isset($ret[$id])){
// save the name of the color
$color = $d['color'];
unset($d['color']);
//save all the item data
$ret[$id] = $d;
// add color to color array
$ret[$id]['color'][] = $color;
}else{
// if wa alredy did all the above things just keep adding colors to color array
$ret[$id]['color'][] = $d['color'];
}
}
foreach($data2 as $d){
//save the id
$id = $d['id'];
//make sure no id was set
if(!isset($ret[$id])){
// save the name of the color
$category = $d['category'];
unset($d['category']);
$ret[$id] = $d;
$ret[$id]['category'][] = $category;
}else{
$ret[$id]['category'][] = $d['category'];
}
}
return $ret;
}
result :
"22": {
"id": "22",
"title": "my products 515151",
"descreption": "5454545455",
"price": "0.05",
"quantity": "2",
"date_added": "2021-01-29 14:37:24",
"primary_image": "http://localhost/ecomerce/uploads/1611927444hat.jpg",
"color": [
"black",
"white",
"pink",
"red",
"yellow"
],
"category": [
"buttom",
"hats",
"shoes"
]
}
Here i want compare two array.
I have two tables one is CATEGORY and second is USER(in which selected multiple category is stored in this format , , , ).
but when the USER want to update their category at that time the earlier selected category should return checked 1 and which is not selected should return checked 0 and here is my code.
case 'cat':
$sql="SELECT category from nesbaty_user where user_id='".$user_id."'";
$qry_res=mysqli_query($con,$sql);
$response1 = array();
while ($array = mysqli_fetch_array($qry_res))
{
foreach (explode(',', $array['category']) as $cat)
{
$response1[]=array('category' => $cat);
$response['Selected_category'] = $response1;
}
}
$qry="SELECT cat_id,category,image_url FROM nesbaty_category";
$qry_res=mysqli_query($con,$qry);
$jsonData = array();
while ($array = mysqli_fetch_assoc($qry_res))
{
$jsonData[] = $array;
$response['category'] = $jsonData;
}
echo json_encode($response);
//echo json_encode(array('data1' =>$response1));
//
mysqli_close($con);
break;
and here is my fetched array from the database.
{
"Selected_category": [
{
"category": "5"
},
{
"category": "6"
},
{
"category": "9"
}
],
"category": [
{
"cat_id": "1",
"category": "Drug",
"image_url": "1.jpg"
},
{
"cat_id": "2",
"category": "Bars",
"image_url": "2.jpg"
},
{
"cat_id": "3",
"category": "Bars",
"image_url": "2.jpg"
},
{
"cat_id": "4",
"category": "Hair Saloon",
"image_url": "2.jpg"
}
]
}
This is for handle this same structure as You provided.
<?php
$response = [];
$sql = "SELECT category from nesbaty_user where user_id='".$user_id."'";
$qry_res = mysqli_query($con, $sql);
$selectedCategories = mysqli_fetch_array($qry_res);
$selectedCategories = explode(',', $selectedCategories['category']);
$qry = "SELECT cat_id,category,image_url FROM nesbaty_category";
$qry_res = mysqli_query($con, $qry);
while ($categories = mysqli_fetch_assoc($qry_res)) {
$categories['checked'] = (int)\in_array($categories['cat_id'], $selectedCategories);
$response[] = $categories;
}
echo json_encode($response);
mysqli_close($con);
If any error writes a comment, I'll fix it.
I need to give output with 'floorno' and 'units' as key.But after performing array_splice operation 'floorno' and 'units' key are replaced by integer values.
How to replace integer-valued key with text floorno and unit.
Below is my code
$floor = "Ground";
$query = "SELECT id,property_no,status FROM property_details WHERE wing ='$A' AND floor ='$floor'";
$execute = $db->query($query);
$ground = $execute->fetchAll(PDO::FETCH_ASSOC);
$block_A = array("floorno"=>$floor,"units"=>$ground);
$floor = "First";
$query = "SELECT id,property_no,status FROM property_details WHERE wing ='$A' AND floor ='$floor'";
$execute = $db->query($query);
$ground = $execute->fetchAll(PDO::FETCH_ASSOC);
$first = array("floorno"=>$floor,"units"=>$ground);
array_splice($block_A,2,0,$first);
Below is my array o/p:
{
"0": "Second",
"1": [
{
"id": "396",
"property_no": "SSC.A.02.01",
"status": "0"
},
{
"id": "397",
"property_no": "SSC.A.02.02",
"status": "0"
}
],
"2": "First",
"3": [
{
"id": "388",
"property_no": "SSC.A.01.01",
"status": "0"
},
{
"id": "389",
"property_no": "SSC.A.01.02",
"status": "0"
}
],
"floorno": "Ground",
"units": [
{
"id": "379",
"property_no": "SSC.A.00.01",
"status": "0"
},
{
"id": "381",
"property_no": "SSC.A.00.02",
"status": "0"
}
]
}
Helper function for splice with assoc
function array_splice_assoc(&$input, $offset, $length, $replacement)
{
$replacement = (array)$replacement;
$key_indices = array_flip(array_keys($input));
if (isset($input[$offset]) && is_string($offset)) {
$offset = $key_indices[$offset];
}
if (isset($input[$length]) && is_string($length)) {
$length = $key_indices[$length] - $offset;
}
$input = array_slice($input, 0, $offset, TRUE)
+ $replacement
+ array_slice($input, $offset + $length, NULL, TRUE);
}
how to manage dynamic key in json
[
{
"batch_id": "132",
"benf_id": "ANP-JAI-1190",
"NA3": "",
"NA4": "",
"status": "Y",
"NA5": "",
"datapoint_id": "105",
"status_update_time": "28/8/2017 ",
"user_id": "santoshk",
"pop_id": "40",
"measuring": "1000ltr",
"weight": "100gm"
},
{
"batch_id": "133",
"benf_id": "ANP-JAI-1195",
"NA3": "",
"NA4": "",
"status": "Y",
"NA5": "",
"datapoint_id": "106",
"status_update_time": "28/8/2017 ",
"user_id": "santoshk",
"pop_id": "41",
"water": "1000ltr",
"medicine": "100gm"
}
]
// my php code
public function benf_status_update($jdata)
{
$count=0;
$this->load->model('m_sf_user');
while($count < count($jdata))
{
$batch_id = $jdata[$count]->batch_id;
$benf_id = $jdata[$count]->benf_id;
$m3=$jdata[$count]->NA3;
$m4=$jdata[$count]->NA4;
$status = $jdata[$count]->status;
$m5=$jdata[$count]->NA5;
$m1=$jdata[$count]->0;
$m2=$jdata[$count]->0;
$datapoint_id = $jdata[$count]->datapoint_id;
$status_update_time = $jdata[$count]->status_update_time;
$user_id =$jdata[$count]->user_id;
$pop_id = $jdata[$count]->pop_id;
$benf_id = substr($benf_id,8,strlen($benf_id));
$qry = "UPDATE pop_b_m_points a JOIN m_pop_batch b ON
b.pop_id=".$pop_id."
and b.batch_id=".$batch_id."
and a.data_p_id=b.dpoint_id
and a.benf_id=".$benf_id."
and a.m_point_id=".$datapoint_id."
SET a.status='".$status."',
a.m1='".$m1."',
a.m2='".$m2."',
a.m3='".$m3."',
a.m4='".$m4."',
a.m5='".$m5."' ,
a.update_time= (SELECT (DATE_FORMAT(STR_TO_DATE('".$status_update_time."', '%d/%m/%Y' ), '%Y%m%d')))";
$this->m_sf_user->jSONservices_u($qry);
$count++;
}
$x=array('json_status'=>"success");
echo json_encode($x);
}
You can simply use json_decode
json_decode($string) to convert String into Array/Object (stdClass).
Example:
$myRawJson = '{
"batch_id": "133",
"benf_id": "ANP-JAI-1195",
"NA3": "",
"NA4": "",
"status": "Y",
"NA5": "",
"datapoint_id": "106",
"status_update_time": "28/8/2017 ",
"user_id": "santoshk",
"pop_id": "41",
"water": "1000ltr",
"medicine": "100gm"
}';
$myAssoc = json_decode($myRawJson);
$myObject = (object)(json_decode($myRawJson));
var_dump($myAssoc['medicine']); //100gm
var_dump($myObject->medicine); //100gm
If you don't know for sure which columns you will get, but do want to save all. Then make an extra column 'data' in which you save the complete set of data through json_encode()
If you can make sure some fields are always there, use them in seperate columns in order to filter and order by those, but also use the data column to add the complete data set.
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() .'}}';
}
}