Related
My php file has code look like this
<?php
$connect = mysqli_connect("localhost","root","","surveytest");
$query = '';
$table_data = '';
$filename2 = "employee_data.js";
$data2 = file_get_contents($filename2);
$array2 = json_decode($data2, true);
foreach($array2 as $row) //Extract the Array Values by using Foreach Loop
{
$query .= "INSERT INTO survey(name, gender, designation)
VALUES
('".$row["name"]."',
'".$row["gender"]."',
'".$row["designation"]."'); "; // Make Multiple Insert Query
$table_data .= '
<tr>
<td>'.$row["name"].'</td>
<td>'.$row["gender"].'</td>
<td>'.$row["designation"].'</td>
</tr>
'; //Data for display on Web page
}
if(mysqli_multi_query($connect, $query)) //Run Mutliple Insert Query
{
echo '<h3>Imported JSON Data</h3><br />';
echo '
<table class="table table-bordered">
<tr>
<th width="45%">Name</th>
<th width="10%">Gender</th>
<th width="45%">Designation</th>
</tr>
';
echo $table_data;
echo '</table>';
}
?>
My javascript file has code look like this
var json =
{
"items": [
{
"name": "Rusydi",
"gender": "Male",
"designation": "System Architect"
},
{
"name": "Hakim",
"gender": "Male",
"designation": "Conservation worker"
}
]
}
Hey! i am a beginner for javascript and JSON.
I try to add var json into mysql database.
Now i want to refer to this javascriptfile(var json) but it's don't work.
My purpose is try to stored this variable in mysql.
That's why i try to do like this.
var json = {
questions: [
{
name: "name",
type: "text",
title: "Please enter your name:",
placeHolder: "Jon Snow",
isRequired: true
}, {
name: "birthdate",
type: "text",
inputType: "date",
title: "Your birthdate:",
isRequired: true
}, {
name: "color",
type: "text",
inputType: "color",
title: "Your favorite color:"
}, {
name: "email",
type: "text",
inputType: "email",
title: "Your e-mail:",
placeHolder: "jon.snow#nightwatch.org",
isRequired: true,
validators: [
{
type: "email"
}
]
}
]
};
This is full code.
https://surveyjs.io/Examples/Library/?id=questiontype-text&platform=jQuery&theme=default
Survey
.StylesManager
.applyTheme("default");
var json = {
questions: [
{
name: "name",
type: "text",
title: "Please enter your name:",
placeHolder: "Jon Snow",
isRequired: true
}, {
name: "birthdate",
type: "text",
inputType: "date",
title: "Your birthdate:",
isRequired: true
}, {
name: "color",
type: "text",
inputType: "color",
title: "Your favorite color:"
}, {
name: "email",
type: "text",
inputType: "email",
title: "Your e-mail:",
placeHolder: "jon.snow#nightwatch.org",
isRequired: true,
validators: [
{
type: "email"
}
]
}
]
};
window.survey = new Survey.Model(json);
survey
.onComplete
.add(function (result) {
document
.querySelector('#surveyResult')
.innerHTML = "result: " + JSON.stringify(result.data);
});
$("#surveyElement").Survey({model: survey});
or what should i do?
Remove the "var json =" from your file and change the extension to ".json" instead of ".js".
Since your javascript file does not contain a valid JSON string it cannot be decoded by php.
employee_data.json
{
"items": [
{
"name": "Rusydi",
"gender": "Male",
"designation": "System Architect"
},
{
"name": "Hakim",
"gender": "Male",
"designation": "Conservation worker"
}
]
}
Ok the problem as I see it is this:
//employee_data.js
var json =
{
And then you import that
$filename2 = "employee_data.js";
$data2 = file_get_contents($filename2);
$array2 = json_decode($data2, true);
JSON is not JavaScript code (strictly speaking), it's way to format or encode JavaScript objects as strings. (JavaScript Object Notation). So your file should start with { and not a variable setting. So you just need to remove that var json = bit.
If you check var_dump($array2); it will probably say NULL and if you check echo json_last_error_msg() right after doing json_decode it will probably say something like Syntax error invalid JSON etc..
This can be reproduced like this:
var_dump(json_decode('var json={"foo":"bar"}', true));
echo json_last_error_msg();
Output:
NULL
Syntax error
Sandbox
If you remove the var json = from my overly simple example, you get this:
array(1) {
["foo"]=> string(3) "bar"
}
No error
Cheers!
First, isolate the json data which immediately follows var json = and ends with } which is followed immediately by ;.
Then repair the json string by wrapping all of the keys in double quotes.
Finally, convert the data to an array so that you can perform your query process with the questions subarrays.
*Note, I DO NOT recommend that you use mysqli_multi_query() because it is unstable/insecure. I recommend that you use a prepared statement to INSERT your data. I will refrain from explaining this task because there are many, many examples of how to do this on StackOverflow.
Code: (PHP Demo) (Regex 1 Demo) (Regex 2 Demo)
if (preg_match('~^var json = \K{.*?}(?=;)~ms', $js_file_contents, $match)) { // cut away extra
$json = preg_replace('~^\s*\K\w+~m', '"\0"', $match[0]); // quote-wrap the keys
var_export(json_decode($json, true)); // convert json string to array and display
}
Output:
array (
'questions' =>
array (
0 =>
array (
'name' => 'name',
'type' => 'text',
'title' => 'Please enter your name:',
'placeHolder' => 'Jon Snow',
'isRequired' => true,
),
1 =>
array (
'name' => 'birthdate',
'type' => 'text',
'inputType' => 'date',
'title' => 'Your birthdate:',
'isRequired' => true,
),
2 =>
array (
'name' => 'color',
'type' => 'text',
'inputType' => 'color',
'title' => 'Your favorite color:',
),
3 =>
array (
'name' => 'email',
'type' => 'text',
'inputType' => 'email',
'title' => 'Your e-mail:',
'placeHolder' => 'jon.snow#nightwatch.org',
'isRequired' => true,
'validators' =>
array (
0 =>
array (
'type' => 'email',
),
),
),
),
)
I'm utilizing Mustache to template some XML responses for an API. I was wondering how I could use the XML template below to render data from this array?
The data is not rendering at all when using this code:
$result = $m->render($template, $r);
echo $result;
Here is JSON converted data:
[
{
"UUID": "655482ab-38ee-433f-b310-1f6f227113b9",
"RefUUID": "92a8ecf6-8eb6-4d1e-b88d-59b50c3b0cc9",
"company":"UAR",
"itemname":"DOOR ",
"daysinstock":"41",
"condition":"A",
"stocknumber":"F0049356",
"ic":"120-00409AL",
"price":"750.00",
"quantity":"1",
"location":"U3020",
"comments": "comment for #0"
},
{
"UUID": "655482ab-38ee-433f-b310-1f6f227113b9",
"RefUUID": "92a8ecf6-8eb6-4d1e-b88d-59b50c3b0cc9",
"company":"UAR",
"itemname":"DOOR ",
"daysinstock":"68",
"condition":"C",
"stocknumber":"F0048586",
"ic":"120-00409AL",
"price":"750.00",
"quantity":"1",
"location":"KEEP"
"comments": "comment for #1"
},
{
"UUID": "655482ab-38ee-433f-b310-1f6f227113b9",
"RefUUID": "92a8ecf6-8eb6-4d1e-b88d-59b50c3b0cc9",
"company":"UAR",
"itemname":"DOOR ",
"daysinstock":"280",
"condition":"B",
"stocknumber":"171013",
"ic":"120-00409AL",
"price":"750.00",
"quantity":"1",
"location":"YCR4"
"comments": "comment for #2"
}
]
XML template trying to render
$template = '<SupplierResponse>
<QuotedPartList>
{{#parts}}
<QuotedPart>
<BMSObject>
<UUID>{{UUID}}</UUID>
<RefUUID>{{RefUUID}}</RefUUID>
</BMSObject>
<SupplierResponseCode>AsRequested</SupplierResponseCode>
<SupplierRefLineNum>{{SupplierRefLineNum}}</SupplierRefLineNum>
<PartNumInfo>
<PartNumType>Stock</PartNumType>
<PartNum>{{stocknumber}}</PartNum>
</PartNumInfo>
<PartNumInfo>
<PartNumType>IC</PartNumType>
<PartNum>{{ic}}</PartNum>
</PartNumInfo>
<PartType>PAL</PartType>
<PartDesc>{{itemname}}</PartDesc>
<PriceInfo>
<UnitListPrice>{{price}}</UnitListPrice>
<UnitNetPrice>{{price}}</UnitNetPrice>
</PriceInfo>
<RInfo>
<Grade>{{condition}}</Grade>
<DaysInStock>{{daysinstock}}</DaysInStock>
<PartLocation>{{location}}</PartLocation>
<PartStore>{{company}}</PartStore>
</RInfo>
<Availability>
<Quantity>{{quantity}}</Quantity>
<InventoryStatus>Available</InventoryStatus>
<AvailableShipDate>2018-05-10</AvailableShipDate>
</Availability>
<LineNoteInfo>
<LineNoteMemo>{{comments}}</LineNoteMemo>
</LineNoteInfo>
</QuotedPart>
{{/parts}}
</QuotedPartList>
</SupplierResponse>';
Edit: Based on new information that came to light after I posted this answer - your issue occurred because Mustache requires data to be stored in an associative array.
// Not correct
$data = [
[
'Foo' => 'Bar'
],
[
'Biz' => 'Buz'
],
]
// Correct
$data = [
'MyData' => [
[
'Foo' => 'Bar'
],
[
'Biz' => 'Buz'
]
]
]
You could try something like this:
<?php
$objectToPassIn = [
'parts' => [
// .. your data here
]
];
// Load template and initialize Mustache
$m = new Mustache_Engine(array(
'loader' => new Mustache_Loader_FilesystemLoader('path/to/where/template/is/stored', array('extension' => '.xml'))
));
$rendered = $m->render(
'template-name-without-file-extension',
$objectToPassIn
);
Finally got it fixed. The data was not formatted correctly:
Data:
$r = array("parts"=> array(
"UUID"=> "655482ab-38ee-433f-b310-1f6f227113b9",
"RefUUID"=> "92a8ecf6-8eb6-4d1e-b88d-59b50c3b0cc9",
"company"=>"UAR",
"itemname"=>"DOOR ",
"daysinstock"=>"41",
"condition"=>"A",
"stocknumber"=>"F0049356",
"ic"=>"120-00409AL",
"price"=>"750.00",
"quantity"=>"1",
"location"=>"U3020",
"comments"=> "comment for #0",
"SupplierRefNum"=> 1
),
array(
"UUID"=> "655482ab-38ee-433f-b310-1f6f227113b9",
"RefUUID"=> "92a8ecf6-8eb6-4d1e-b88d-59b50c3b0cc9",
"company"=>"UAR",
"itemname"=>"DOOR ",
"daysinstock"=>"68",
"condition"=>"C",
"stocknumber"=>"F0048586",
"ic"=>"120-00409AL",
"price"=>"750.00",
"quantity"=>"1",
"location"=>"KEEP",
"comments"=> "comment for #1",
"SupplierRefNum"=> 2
),
array(
"UUID"=> "655482ab-38ee-433f-b310-1f6f227113b9",
"RefUUID"=> "92a8ecf6-8eb6-4d1e-b88d-59b50c3b0cc9",
"company"=>"UAR",
"itemname"=>"DOOR ",
"daysinstock"=>"280",
"condition"=>"B",
"stocknumber"=>"171013",
"ic"=>"120-00409AL",
"price"=>"750.00",
"quantity"=>"1",
"location"=>"YCR4",
"comments"=> "comment for #2",
"SupplierRefNum"=> 3
}
}
);
Code:
$result = $m->render($template, $r); // Used same template as in my original post.
I am android developer and new in PHP. I don't know PHP very well. I create
<?php
header('Content-Type: application/json; charset=utf-8');
$mysqli = new mysqli ('localhost', 'mabhi', '9993', 'general');
//PROBLEM LANGUAGE ?????
if (function_exists('mysql_set_charset')) {
mysqli_set_charset($mysqli, 'utf8');
} else {
mysqli_query($mysqli, "SET NAMES 'utf8'");
}
// Check if album id is posted as GET parameter
$myq = $mysqli->query('SELECT * FROM Ages');
while ($myr = $myq->fetch_assoc()) {
$array["Questions"][] = (array(
'Question' => $myr['Question'],
'Answer' => $myr['option1'],
'Answer' => $myr['option2'],
'Answer' => $myr['option3'],
'Answer' => $myr['option4'],
'CorrectAnswer' => $myr['CorrectAnswer'],
));
}
echo json_encode($array, JSON_UNESCAPED_UNICODE);
?>
output:
{
"Questions": [
{
"Question": "sfsa sfd s sdf",
"Answer": "vvv",
"CorrectAnswer": null
},
{
"Question": "dsfgdsfgv dsf dfs",
"Answer": "vvvv vv",
"CorrectAnswer": null
}
]
}
But I would like json output in below format: Answer are displayed multiple times for each question. Please suggest me what changes in my code.
{
"Questions": [
{
"Question": "dfsfdsfgv dfsfsd dfs sf",
"CorrectAnswer": 3,
"Answers": [
{
"Answer": "vvvvvvv"
},
{
"Answer": "vvv"
},
{
"Answer": "vv"
},
{
"Answer": "v"
}
]
},
{
"Question": "dgdsgdsgdsgszdfvgfvds",
"CorrectAnswer": 0,
"Answers": [
{
"Answer": "Lee"
},
{
"Answer": "Wrangler"
},
{
"Answer": "Levi's"
},
{
"Answer": "Diesel"
}
]
}
]
}
As pointed by jereon, you are overwriting the value of Answer key. You need to create a separate array for the all the Answers together.
Change
$array["Questions"][] = (array(
'Question' => $myr['Question'],
'Answer' => $myr['option1'],
'Answer' => $myr['option2'],
'Answer' => $myr['option3'],
'Answer' => $myr['option4'],
'CorrectAnswer' => $myr['CorrectAnswer'],
));
to
$array["Questions"][] = (array(
'Question' => $myr['Question'],
'Answers' => array((object)array('Answer' => $myr['option1']),
(object)array('Answer' => $myr['option2']),
(object)array('Answer' => $myr['option3']),
(object)array('Answer' => $myr['option4'])),
'CorrectAnswer' => $myr['CorrectAnswer'],
));
You should not assign multiple array elements with the same identifier ("Answer") as they would just overwrite each other. I would suggest you to use a non-associative array for the Answers so that your target JSON would look like this:
{
"Questions": [
{
"Question": "dfsfdsfgv dfsfsd dfs sf",
"CorrectAnswer": 3,
"Answers": [
"vvvvvvv",
"vvv",
"vv",
"v"
]
},
{
"Question": "dgdsgdsgdsgszdfvgfvds",
"CorrectAnswer": 0,
"Answers": [
"Lee",
"Wrangler",
"Levi's",
"Diesel"
]
}
]
}
Therefore you would use the following PHP code for the loop:
$array = array();
while ($myr = $myq->fetch_assoc()) {
$array["Questions"][] = array(
'Question' => $myr['Question'],
'CorrectAnswer' => $myr['CorrectAnswer'],
'Answers' => array(
$myr['option1'],
$myr['option2'],
$myr['option3'],
$myr['option4'],
),
);
}
First thing you are doing wrong is you are overwriting the value of answer options so what will happen is when your 1st option will be overwritten by 2nd option, 2nd option with 3rd and 3rd option with 4th option. So you will have to create an array for answers and push every answer in that array and in the end assign this answer option array to answer. So your code should look like below
while ( $myr = $myq->fetch_assoc () ) {
$answers_array=new array();
$answer_option=new stdClass(); // Create a object to format in required format and use this object to store every option of answer
$answer_option->answer=$myr['option1'];
array_push($answers_array,$answer_option);
$answer_option->answer=$myr['option2'];
array_push($answers_array, $answer_option);
$answer_option->answer=$myr['option3'];
array_push($answers_array, $answer_option);
$answer_option->answer=$myr['option4'];
array_push($answers_array,$answer_option);
$array["Questions"][] = array(
'Question' => $myr['Question'],
'CorrectAnswer' => $myr['CorrectAnswer'],
'answers' => $answers_array;
);
}
CakePHP API returns result like this:
{
"status": "OK",
"themes": [
{
"Theme": {
"id": "20",
"user_id": "50",
"name": "dwdwdw",
"language_code_from": "cz",
"language_code_to": "en",
"type": "CUSTOM",
"created": "2014-10-19 15:36:05",
"count_of_cards": 0
}
}
]
}
I would like to ask, how can in remove nested Theme object to get result like this?:
{
"status": "OK",
"themes": [
{
"id": "20",
"user_id": "50",
"name": "dwdwdw",
"language_code_from": "cz",
"language_code_to": "en",
"type": "CUSTOM",
"created": "2014-10-19 15:36:05",
"count_of_cards": 0
}
]
}
Here is my CakePHP code:
$this->Theme->recursive = -1;
// GET USER ID
$themeData['user_id'] = $isSessionValid;
// GET ALL THEMES RELATED TO USER
$foundThemes = $this->Theme->find('all', array(
'conditions' => array(
'Theme.user_id' => $themeData['user_id'])
)
);
$themes = array();
// FOREACH THEMES AND GET COUNT FOR CARDS FOR EACH THEME
foreach($foundThemes as $foundTheme) {
// GET COUNT OF QUESTIONS FOR ACTUAL THEME
$countOfCards = $this->Theme->Card->find('count', array(
'conditions' => array(
'Card.theme_id' => $foundTheme['Theme']['id'])
)
);
// APPEND TO ACTUAL ARRAY
$foundTheme['Theme']['count_of_cards'] = $countOfCards;
array_push($themes,$foundTheme);
}
// SET SUCCESS RESPOSNSE
$this->set(array(
'status' => 'OK',
'themes' => $themes,
'_serialize' => array(
'status',
'themes',
)
));
Many thanks for any advice.
You can manipulate CakePHP's array formats using its built in Hash utility: http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash
What I would do would be to flatten the results:
$results = Hash::flatten($results);
Your data array will end up as a single dimensional array looking like this:
$results = array(
'status' => 'OK'
'themes.0.Theme.id' => 20,
...
'themes.1.Theme.id' => 21,
...
);
You can then use string replace to remove "Theme" from your keys:
$keys = array_keys($results);
$keys = str_replace('Theme.', '', $keys);
Then you can use Hash::expand to get your original array, now formatted how you want:
$results = Hash::expand(array_combine($keys, array_values($results)));
I dont think CakePHP supports this. if you want to do this with an easy way check the Set Utility.
http://book.cakephp.org/2.0/en/core-utility-libraries/set.html
I'm trying to adjust the timezone with date aggregation operators.
I need to make -7 hours adjustment on the $signs.timestamp field.
This is my code:
function statsSignatures() {
$cursor = $this->db->collection->users->aggregate(
array('$unwind' => '$signs'),
array('$project'=>array(
'signs'=>'$signs',
'y'=>array('$year'=>'$signs.timestamp'),
'm'=>array('$month'=>'$signs.timestamp'),
'd'=>array('$dayOfMonth'=>'$signs.timestamp'),
'h'=>array('$hour'=>'$signs.timestamp')
)),
array('$group'=>array(
'_id'=>array('year'=>'$y','month'=>'$m','day'=>'$d','hour'=>'$h'),
'total'=>array('$sum'=>1)
)),
array('$sort'=>array(
'_id.year'=>1,
'_id.month'=>1,
'_id.day'=>1,
'_id.hour'=>1
))
);
return $cursor['result'];
}
I'm using MongoDB version 2.6.3.
Thank you a lot !
You can use $project with $subtract operator to make a -7 hour adjustment to a Date field:
{
$project : {
ts : { $subtract : [ "$signs.timestamp", 25200000 ] }
}
}
// 25200000 == 1000 milis x 60 sec x 60 mins x 7 h
The projected field ts is a Date that's offset by -7 hours.
Edit
This is the correct PHP syntax when using $subtract.
array(
'$project' => array(
'ts' => array('$subtract' => array('$signs.timestamp', 25200000))
)
)
Subtract accepts an array of values, not a key=>value pair.
I'm not sure why, but I'm getting "exception: invalid operator '$signs.timestamp'" if i'm trying to subtract this in php like this code:
$cursor = $app['mdb']->changemi->users->aggregate(
array('$unwind' => '$signs'),
array('$project' => array(
'ts'=>array('$subtract'=>array(
'$signs.timestamp'=> 25200000
))
)),
array('$project'=>array(
'y'=>array('$year'=>'$ts'),
'm'=>array('$month'=>'$ts'),
'd'=>array('$dayOfMonth'=>'$ts'),
'h'=>array('$hour'=>'$ts')
)),
array('$group'=>array(
'_id'=>array('year'=>'$y','month'=>'$m','day'=>'$d','hour'=>'$h'),
'total'=>array('$sum'=>1)
)),
array('$sort'=>array(
'_id.year'=>1,
'_id.month'=>1,
'_id.day'=>1,
'_id.hour'=>1
))
);
So I came with 2 workarounds:
backend php. json_decode
$cursor = $app['mdb']->changemi->users->aggregate(
array('$unwind' => '$signs'),
json_decode('{"$project" : {"ts" : { "$subtract" : [ "$signs.timestamp", 25200000 ] }}}',true),
array('$project'=>array(
'y'=>array('$year'=>'$ts'),
'm'=>array('$month'=>'$ts'),
'd'=>array('$dayOfMonth'=>'$ts'),
'h'=>array('$hour'=>'$ts')
)),
array('$group'=>array(
'_id'=>array('year'=>'$y','month'=>'$m','day'=>'$d','hour'=>'$h'),
'total'=>array('$sum'=>1)
)),
array('$sort'=>array(
'_id.year'=>1,
'_id.month'=>1,
'_id.day'=>1,
'_id.hour'=>1
))
);
frontend javascript (minusHours)
Date.prototype.minusHours= function(h){
this.setHours(this.getHours()-h);
return this;
}
...
"date": new Date({{ i._id.year }}, {{ i._id.month -1 }}, {{ i._id.day }}, {{ i._id.hour }}, 0, 0, 0).minusHours(7),
Here is what worked for me. Instead of doing the timezone conversion in the 'project', I just convert the timestamp while grouping.
group._id = {
year: { $year : [{ $subtract: [ "$timestamp", 25200000 ]}] },
month: { $month : [{ $subtract: [ "$timestamp", 25200000 ]}] },
day: { $dayOfMonth : [{ $subtract: [ "$timestamp", 25200000 ]}] }
};
group.count = {
$sum : 1
};
There's no need to close some objects in array, this way worked for me:
group._id = {
year: { $year : { $subtract: [ "$timestamp", 25200000 ]}},
month: { $month : { $subtract: [ "$timestamp", 25200000 ]}},
day: { $dayOfMonth : { $subtract: [ "$timestamp", 25200000 ]}}
};
group.count = {
$sum : 1
};