I have a strange issue when I'm trying to update a json in my database.
This is my code :
// Update content of user cart
$contentJSON = json_decode($userCart['content'],true);
$newJSONContent;
$wineNotExist = true;
$index = 1;
foreach($contentJSON as $key) {
// Update content if wine is already in user cart
if ($key['wineId'] === $wineId) {
$contentObject->wineId = $wineId;
$contentObject->wineQuantity = $key['wineQuantity'] + $wineQuantity;
$dataIndex = strval($index);
$newJSONContent->$dataIndex = $contentObject;
$wineNotExist = false;
} else {
$contentObject->wineId = $key['wineId'];
$contentObject->wineQuantity = $key['wineQuantity'];
$dataIndex = strval($index);
$newJSONContent->$dataIndex = $contentObject;
}
$index++;
}
if ($wineNotExist) {
$dataKey = strval($index);
$contentObject->wineId = $wineId;
$contentObject->wineQuantity = $wineQuantity;
$newJSONContent->$dataKey = $contentObject;
}
So, I decided to build a new JSON and parse the former; moreover if json not contains the wineId we created a new data input in JSON but this section replaces previous key by the right one and create the right one as you can see in AJAX response here :
Response when it's the same wineId
{
"code": 200,
"status": "success",
"message": "This wine has been added to your cart",
"content": {
"1": {
"wineId": 2,
"wineQuantity": 3
}
},
"index": true
}
Response when wineId is not contains in cart
{
"code": 200,
"status": "success",
"message": "This wine has been added to your cart",
"content": {
"1": {
"wineId": 5,
"wineQuantity": 1
},
"2": {
"wineId": 5,
"wineQuantity": 1
}
},
"index": true
}
I don't understand why the instruction in if replaces previous value, do you have an idea why ?
When I use another variable name for contentObject in if instruction, the code works but why ? Because $contentObject is a local variable in foreach loop
Sorry for my english, I'm French.
It works with this code, so the problem is that $contentObject has the previous value whereas it's a local varibale, is it specific to PHP ?
// Update content of user cart
$contentJSON = json_decode($userCart['content'],true);
$newJSONContent;
$wineNotExist = true;
$index = 1;
foreach($contentJSON as $key) {
// Update content if wine is already in user cart
if ($key['wineId'] === $wineId) {
$contentObject=null;
$contentObject->wineId = $wineId;
$contentObject->wineQuantity = $key['wineQuantity'] + $wineQuantity;
$dataIndex = strval($index);
$newJSONContent->$dataIndex = $contentObject;
$wineNotExist = false;
} else {
$contentObject=null;
$contentObject->wineId = $key['wineId'];
$contentObject->wineQuantity = $key['wineQuantity'];
$dataIndex = strval($index);
$newJSONContent->$dataIndex = $contentObject;
}
$index++;
}
if ($wineNotExist) {
$contentObject=null;
$dataKey = strval($index);
$contentObject->wineId = $wineId;
$contentObject->wineQuantity = $wineQuantity;
$newJSONContent->$dataKey = $contentObject;
}
Related
I have a json file stored on server & it looks like below:
{
"support_link":"#",
"support_link_2":"#",
"packs":[
{
"identifier":1,
"viewCount":0,
"downloadCount":0
},
{
"identifier":2,
"viewCount":0,
"downloadCount":0
}
]
}
By using PHP, I want to update the viewCount & downloadCount of some of the arrays inside packs.
But the thing is the data is received via a POST method to the server which contains another json with info. of which identifier to update & what param to update, & I am not able to update the existing file & save it back.
Received Json format:
{
"impressions": [
{
"identifier": "1",
"impressionCount": 2
},
{
"identifier": "100",
"impressionCount": 2
},
{
"identifier": "1000",
"impressionCount": 2000
}
],
"downloads": [
{
"identifier": "1",
"downloadCount": 10
}
]
}
What I've tried to do so far:
$json = file_get_contents('php://input');
if ($json != '') {
$properJsonFormatted = json_decode($json, true);
$impressions = $properJsonFormatted['impressions'];
$downloads = $properJsonFormatted['downloads'];
$testConfig =
$json = file_get_contents('php://input');
if ($json != '') {
$properJsonFormatted = json_decode($json, true);
$impressions = $properJsonFormatted['impressions'];
$downloads = $properJsonFormatted['downloads'];
$testConfig = json_decode(file_get_contents("test_config.json"),true);
$packs = $testConfig['packs'];
foreach ($packs as &$pack) {
$packIdentifier = $pack['identifier'];
foreach ($impressions as $impression) {
$impressionIdentifier = $impression['identifier'];
if ($packIdentifier == $impressionIdentifier) {
$pack['viewCount'] += $impression['impressionCount'];
$newCount = $pack['viewCount'];
print("Id: $packIdentifier, ViewCount: $newCount\n");
}
}
}
put_file_contents("test_config.json" , $testConfig);
// print_r($testConfig);
// Save back the updated test_config.json
}
}
UPDATE
Seem to have misinterpreted the question. The actual problem seems to be much simpler.
Change this:
put_file_contents("test_config.json" , $testConfig);
To this:
file_put_contents('test_config.json', json_encode($testConfig));
Also change this:
$packs = $testConfig['packs'];
To this:
$packs = &$testConfig['packs'];
As it seems you forgot to assign that by reference, while you correctly did that in the foreach.
I amnot familiar php arrays. Therefore I couldn't solve that problem :
My data comes from database. I didn't post database connection parts, they work perfectly. As I understand I need to use multidimensional array. My Json format should be like this
{
"monthly":[
{
"id":1,
"name":"This is a JSON event",
"startdate":"2016-9-15",
"enddate":"2016-9-15",
"starttime":"12:00",
"endtime":"2:00",
"color":"#FFB128",
"url":""
},
{
"id":2,
"name":"This is a JSON event",
"startdate":"2019-3-25",
"enddate":"2019-3-25",
"starttime":"12:00",
"endtime":"23:00",
"color":"#EF44EF",
"url":""
}
]
}
My PHP script (relevant part) :
try {
$q = "SELECT * FROM eventcalendar";
$res = $db->prepare($q);
$res->execute();
if ($res->rowCount() != 0) {
$data = array('monthly' => array());
$push_array = array();
foreach ($res as $key) {
$data['monthly']['id'] = $key['id'];
$data['monthly']['name'] = $key['name'];
$data['monthly']['startdate'] = $key['startdate'];
$data['monthly']['enddate'] = $key['startdate'];
$data['monthly']['color'] = $key['color'];
$data['monthly']['starttime'] = 12;
$data['monthly']['endtime'] = 12;
$data['monthly']['url'] = "";
array_push($push_array, $data);
}
file_put_contents('../js/events.json', json_encode($push_array));
echo('<div class="alert alert-success resultsuccess" ><h4 class="alert-heading">Successful!</h4></div>');
}
} catch (Exception $e) {
echo('<div class="alert alert-danger resultsuccess" >'.'Error: '.$e->getMessage().'</div>');
}
I get that JSON format
[
{
"monthly":{
"id":"1",
"name":"test1",
"startdate":"2019-03-29",
"enddate":"2019-03-29",
"color":"#ffb128",
"starttime":12,
"endtime":12,
"url":""
}
},
{
"monthly":{
"id":"2",
"name":"test2",
"startdate":"2019-03-29",
"enddate":"2019-03-29",
"color":"#4263e6",
"starttime":12,
"endtime":12,
"url":""
}
}
]
Thanks for reading...
Your problem is that you are creating new arrays with a monthly index on each pass through your loop, instead of pushing the new data into the existing monthly array. Try this instead:
if ($res->rowCount() != 0) {
$push_array = array('monthly' => array());
$data = array();
foreach ($res as $key) {
$data['id'] = $key['id'];
$data['name'] = $key['name'];
$data['startdate'] = $key['startdate'];
$data['enddate'] = $key['startdate'];
$data['color'] = $key['color'];
$data['starttime'] = 12;
$data['endtime'] = 12;
$data['url'] = '';
array_push($push_array['monthly'], $data);
}
My OUTPUT IS
{
"session": true,
"status": true,
"msg": "user data find successfully",
"user_detail": [
{
"user_name": "asad ali",
"user_profile_pic": "localhost/uploads/image/9152108abc",
"follow": false
},
{
"image_path": [
"localhost/uploads/image/1787860Discover All In One.png",
"localhost/uploads/image/7947861Discover All In One.png"
]
},
{
"user_name": "asim kabeer",
"user_profile_pic": "localhost/uploads/image/1952108xyz",
"follow": false,
"image_path": [
"localhost/uploads/image/6547860Discover All In One.png",
"localhost/uploads/image/2152108Mart Zone - All in one.png"
]
},
My Code is
while ($rowb = $resultb->fetch_assoc())
{
$userid = $rowb['user_id'];
$user_name = $rowb['fast_name']." ".$rowb['last_name'];
$user_pic_path=$rowb['user_pic_path'];
$user_follow=$rowb['follower_id'];
$image_path=$rowb['image_path'];
if($user_follow == $user_id)
{
$user_followi = TRUE;
}
elseif($user_follow !== $user_id)
{
$user_followi = FALSE;
}
if(!isset($result[$userid]))
{
$result[] = array('user_name'=>$user_name,'user_profile_pic'=>$user_pic_path,'follow'=>$user_followi);
}
$result[$userid]['image_path'][] = $image_path;
}
$response['session']=TRUE;
$response['status']=TRUE;
$response['msg']="user data find successfully";
$response['user_detail']=$result;
echo json_encode($response);
Issue is
i want to remove gap between follow & image path in first user asad ali
if you see all image path with no gap but 1st user asad ali have 2 line gap between follow & image_path see my output
When you use $result[] = x; php add x to end of numeric index.
If you want initiate $result for user you must use:
if(!isset($result[$userid]))
{
$result[$userid] = array('user_name'=>$user_name,'user_profile_pic'=>$user_pic_path,'follow'=>$user_followi, 'image_path'=>[]);
}
$result[$userid]['image_path'][] = $image_path;
You are using $user_id in your code which will definitely have any value. You are using that as a key in
$result[$userid]['image_path'][] = $image_path;
So you have to remove $user_id so avoid index.
You can use :
if(!isset($result[$userid]))
{
$data = array('user_name'=>$user_name,'user_profile_pic'=>$user_pic_path,'follow'=>$user_followi);
$result[] = $data;
$image_path = array("localhost/uploads/image/1787860Discover All In One.png","localhost/uploads/image/7947861Discover All In One.png");
}
$result[]['image_path'] = $image_path;
$result = json_encode($result);
This is almost exactly what I want, but that question hasn't been answered and it's been a year. I've managed to get close, I think, but numbers are being printed as keys. In my example it shows up on line 47, but it is repeated for every "course_name" in the actual file.
[
{
"school_name": "Projects",
"terms": [
{
"term_name":"category_name#1",
"departments": [
{
"department_name":"sub_category_name1",
"department_code":"category code text here",
"courses":[
{
"course_name": "project1",
"course_code":"project 1 code text goes here",
"sections":[
{
"section_code":"mike",
"unique_id":"xxx#mail.com"
},
{
"section_code":"dan",
"unique_id":"xxx#gmail.com"
}
]
},
{
"course_name": "project2",
"course_code":"project 2 code text goes here",
"sections":[
{
"section_code":"steve",
"unique_id":"xxx#mail.com"
},
{
"section_code":"chris",
"unique_id":"xxx#gmail.com"
}
]
}
]
},
{
"department_name": "sub_category_name2",
"department_code":"sub category description text goes here..",
"courses": {
-->>> "69": {
"course_name": "project3",
"course_code":"project3 code text goes here ",
"sections":[
{
"section_code":"Alex",
"unique_id":"xxx#gmail.com"
}
]
}
}
}
]
}
]
}
]
Here is the query I am using and an example of data being returned.
SELECT school_name, term_name, department_name, department_code, course_code, course_name, section_code, magento_course_id
FROM schools INNER JOIN term_names ON schools.id=term_names.school_id INNER JOIN departments ON schools.id=departments.school_id INNER JOIN
adoptions ON departments.id=adoptions.department_id
"UCA-2" "SPRING 2013" "ACCOUNTING" "ACCT" "3315" "COST ACCOUNTING" "10258" 10311
What I have is being generated with this code.
$row_array = array();
$terms = array();
$departments = array();
$courses = array();
$h = 0;
$i = 0;
$j = 0;
while ($row = mysqli_fetch_assoc($fetch)) {
$row_array[$row['school_name']]['school_name'] = $row['school_name'];
$akey = array_search($row['term_name'], $terms);
if ($akey === FALSE) {
$m = $h++;
$terms[] = $row['term_name'];
$row_array[$row['school_name']]['terms'][$m]['term_name'] = $row['term_name'];
} else {
$m = $akey;
}
$key = array_search($row['department_code'], $departments);
if ($key === FALSE) {
$k = $i++;
$departments[] = $row['department_code'];
$row_array[$row['school_name']]['terms'][$m]['departments'][$k]['department_name'] = $row['department_name'];
$row_array[$row['school_name']]['terms'][$m]['departments'][$k]['department_code'] = $row['department_code'];
} else {
$k = $key;
}
$skey = array_search($row['course_code'], $courses);
if ($skey === FALSE) {
$l = $j++;
$courses[] = $row['course_code'];
$row_array[$row['school_name']]['terms'][$m]['departments'][$k]['courses'][$l]['course_name'] = $row['course_name'];
$row_array[$row['school_name']]['terms'][$m]['departments'][$k]['courses'][$l]['course_code'] = $row['course_code'];
} else {
$l = $skey;
}
$row_array[$row['school_name']]['terms'][$m]['departments'][$k]['courses'][$l]['sections'][] = array('section_code' => $row['section_code'], 'unique_id' => $row['magento_course_id']);
}
How do I generate this JSON without those numbers showing up?
I think you have some key & encoding problems. Too much key usage, excessive loops in your code. Maybe you should tidy your sql query.
Since you are setting keys for courses, JSON shows it.
Try removing the key after "['courses']" in your last line such as;
Change ['courses'][$l] to ['courses'][]
At the end, encode the array for JSON.
$result = json_encode($result);
I am working on a project that previously done with another developer. This project based on PHP Yii framework and mobile side is Android to get JSON messages from the web services that provided in the website.
I'm stuck in this web service function "getStamp"
I don't know what are the JSON response messages. I mean what are the string Values that I'll hold for 'stampID', 'stampName', 'stampImg'.
These are the information that I have:
request parameters:
kioskid
accesstoken
tagid
eventid
checking = 0 or 1
for failed response:
status = 0
message = error message
for success response:
status = 1
tappedStamp = the obtain stamp ID after tapping the device (if checking not equal to 1)
message = the message of the obtained stamp (if checking not equal to 1)
collectedStamp = list of collected stamp ID
If you want to use 'getStamp' web service to do the checking on how
many stamps that have been collected by the user, then you pass
'checking' as 1. If you want to use that web service to collect the
stamp of the kiosk, then you pass 'checking' as 0.
So far as what I understand from the Code and explanation that 'collectedStamp' and 'tappedStamp' are JSON Object names of a JSON Arrays
I need to know these 3 Elements (I suppose to get it from some where the names are random not real I just make it to explain to you what need)
'stampID', 'stampName','stampImg'
{ "collectedStamp" : [ { "stampID" : "1",
"stampName" : "stamp1",
"stampImg": "stamp1.png"
},
{ "stampID" : "2",
"stampName" : "stamp2",
"stampImg": "stamp2.png"
},
],
"status" : "1"
}
{ "tappedStamp" : [ { "stampID" : "1",
"stampName" : "stamp1",
"stampImg": "stamp1.png"
},
{ "stampID" : "2",
"stampName" : "stamp2",
"stampImg": "stamp2.png"
},
],
"status" : "1"
}
For Android Implementation most likely I'll use the same code that I provided in this post
Errors when getting JSON result into ListView
if you see in the web service function in that link you'll find this
$list = array();
foreach($events as $row){
$list[] = array('id'=>$row->id, 'name'=>$row->eventname);
}
$response['status'] = '1';
$response['list'] = $list;
}
which means that that the JSON response['list'] Contains 'id' and 'name' objects
and these are the String values that I add it inside ListView Adapter
I need to know the equivalent to 'id' and 'name' in this web Service
getStamp() Web Service Function:
public function actionGetStamp(){
if(isset($_POST['kioskid']) && isset($_POST['accesstoken']) && isset($_POST['tagid']) && isset($_POST['eventid']) && isset($_POST['checking'])){
$response = array();
$kiosk = Kiosk::model()->findByAttributes(array('kioskid'=>$_POST['kioskid'], 'accesstoken'=>$_POST['accesstoken']));
if(($kiosk === null || $kiosk->eventid != $_POST['eventid']) && $_POST['accesstoken'] != 'REPOST_SYNC'){
$response['status'] = '0';
$response['message'] = 'Invalid Kiosk';
} else {
$eventStation = EventStation::model()->findByAttributes(array('eventid'=>$_POST['eventid'],'deviceid'=>$_POST['kioskid']));
if($eventStation === null){
$response['status'] = '0';
$response['message'] = 'Invalid Kiosk';
} else {
$tag = EventTag::model()->findByAttributes(array('tagid'=>$_POST['tagid'], 'eventid'=>$eventStation->eventid, 'status'=>'A'));
if($tag === null || $tag->joinon == null){
$response['status'] = '0';
$response['message'] = 'Tag is not registered yet.';
} else {
$sql = 'SELECT es.id, (CASE WHEN esc.stampid IS NULL THEN 0 ELSE 1 END) collected,
(CASE WHEN es.kioskid = :kioskid THEN 1 ELSE 0 END) tapped,
es.message
FROM tap_event_stamp es
LEFT JOIN tap_event_stamp_collection esc ON es.id = esc.stampid and esc.tagid = :tagid
WHERE es.eventid = :eventid AND es.isdeleted = 0
GROUP BY es.id ORDER BY es.id
';
$params = array(':eventid'=>$_POST['eventid'], ':kioskid'=>$eventStation->id, ':tagid'=>$tag->id);
$stamps = Yii::app()->db->createCommand($sql)->queryAll(true, $params);
if(sizeof($stamps) == 0){
$response['status'] = '0';
$response['message'] = 'Invalid Request';
} else {
$feature = EventFeatures::model()->findByAttributes(array('eventid'=>$_POST['eventid'],'featureid'=>3));
if($feature === null){
$response['status'] = '0';
$response['message'] = 'Invalid Request';
} else {
$info = json_decode($feature->info, true);
$random = false;
if(isset($info['STAMPSEQ'])){
$random = $info['STAMPSEQ'] == 'R';
}
$collected = array();
$response['status'] = $_POST['checking'] == 1 ? '1' : '0';
$duplicate = false;
foreach($stamps as $stamp){
if ($stamp['tapped'] == 1 && $_POST['checking'] != 1){
$response['tappedStamp'] = $stamp['id'];
$response['message'] = $stamp['message'];
$response['status'] = '1';
$duplicate = $stamp['collected'] == 1;
} elseif($stamp['collected'] == 1){
$collected[] = $stamp['id'];
continue;
} elseif(!$random && $_POST['checking'] != 1){
if( !isset($response['tappedStamp']) ){
$response['message'] = 'You have tapped a wrong kiosk';
}
break;
}
}
if( $response['status'] == '1' ){
$response['collectedStamp'] = $collected;
if(!$duplicate && $_POST['checking'] != 1){
$newRecord = new StampCollection();
$newRecord->eventid = $_POST['eventid'];
$newRecord->tagid = $tag->id;
$newRecord->kioskid = $eventStation->id;
$newRecord->stampid = $response['tappedStamp'];
$newRecord->collectedon = time();
$newRecord->save();
}
}
if( $response['status'] == '1' && Yii::app()->params['isOffline'] && $_POST['checking'] != 1){
$params = array();
$params['tagid'] = $_POST['tagid'];
$params['eventid'] = $_POST['eventid'];
$params['kioskid'] = $_POST['kioskid'];
$params['accesstoken'] = 'REPOST_SYNC';
$model = new PendingRequest();
$model->request_url = '/ws/getStamp';
$model->request_param = json_encode($params);
$model->createdon = time();
$model->issent = 0;
$model->save();
}
}
}
}
}
}
$this->_sendResponse(200, CJSON::encode($response));
} else {
$this->_sendResponse(400);
}
}
One more question:
How can I check the web service from the Browser and pass the parameter (this Project uses Yii Framework)? So I can get JSON message either from browser.
Update:
After using "POSTMAN REST Client" I got this message
if checking = 1
{"status":"1","collectedStamp":[]}
if checking = 0
this is the HTML Code I got
https://drive.google.com/file/d/0B0rJZJK8qFz9MENzcWxhU3NPalk/edit?usp=sharing