Encode PHP array from MySQL to JSON - php

I've been trying to learn how to convert MySQL query results to JSON arrays in PHP and I haven't managed to make much progress.
Basically I'm trying to convert the results of this query into an array:
$sql = mysql_query("SELECT `status` FROM jobs");
while($row = mysql_fetch_array($sql)){
$job_status = $row['status'];
}
Into this:
$data = array(
array( 'label'=> "a", 'data'=> 1), // The data values are queried using PHP and SQL
array( 'label'=> "b", 'data'=> 2),
array( 'label'=> "c", 'data'=> 3)
);
echo json_encode($data);
The $data array will be used display the values in the float chart. The code is shown below:
if($("#piechart").length)
{
$.plot($("#piechart"), data,
{
series: {
pie: {
show: true
}
},
grid: {
hoverable: true,
clickable: true
},
legend: {
show: false
},
colors: ["#FA5833", "#2FABE9", "#FABB3D", "#78CD51"]
});
Below is the JS code that is converted into a PHP array and the encoded using JSON.
var data = [
{ label: "a", data: 1},
{ label: "b", data: 2},
{ label: "c", data: 3},
Any help would be greatly appreciated!

mysql_fetch_assoc might work better

Related

Merge and transpose data from 2 arrays to create a new structure with header data as the first row

I wanna combine data array and series array to another dataset like source array,
in Laravel,
to draw charts, data is the axis, series are the item contents,
I wanna reassemble these data so that they fit the data type of ECharts
https://echarts.apache.org/en/tutorial.html#Dataset, the ref is here,
can you show how to convert it,thanks
data: ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie']
series: [
{
name: '2015',
data: [89.3, 92.1, 94.4, 85.4]
},
{
name: '2016',
data: [95.8, 89.4, 91.2, 76.9]
},
{
name: '2017',
data: [97.7, 83.1, 92.5, 78.1]
}
]
<!-- result -->
source: [
['name', '2015', '2016', '2017'],
['Mha Latte', 89.3, 95.8, 97.7],
['Milk Tea', 92.1, 89.4, 83.1],
['Cheese Cocoa', 94.4, 91.2, 92.5],
['Walnut Brownie', 85.4, 76.9, 78.1]
]
$data = ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie'];
$series = [
[
'name' => '2015',
'data' => [89.3, 92.1, 94.4, 85.4]
],
[
'name' => '2016',
'data' => [95.8, 89.4, 91.2, 76.9]
],
[
'name' => '2017',
'data' => [97.7, 83.1, 92.5, 78.1]
],
];
$first = array_merge(['name'], array_map(function ($a) {
return $a['name'];
}, $series));
$other = array_map(function ($a, $index) use ($series) {
return array_merge([$a], array_map(function ($b) use ($index) {
return $b['data'][$index];
}, $series));
}, $data, array_keys($data));
$result = array_merge([$first], $other);
Isolate the data column from $series.
Transpose the data column array along with the $data array.
Prepend a row to that result of step #2 which contains the static word name then the year values from the name column of $series.
Code: (Demo)
$result = array_map(null, $data, ...array_column($series, 'data')); // non-header data
array_unshift($result, array_merge(['name'], array_column($series, 'name'))); // header data
var_export($result);

How to refer JSON used with PHP and stored the surveyjs in mysql

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',
),
),
),
),
)

how to display an array on view page after running function returning to same page

i have a page called "grapghhehe" and in that page i have a bar chart and a form for user to select 2 dates(from and to) so when user selects this 2 dates it suppose to show the graph details based on the dates only.. so what i have done where it will return the data which is correct in an array like:
array:3 [
0 => 1
1 => 17
2 => 1
]
array:1 [
0 => 3
]
array:4 [
0 => 1
1 => 2
2 => 1
3 => 1
]
so as you can they are 3 arrays for 3 different values... now i want to return this data on the same page. how can i do that? my code so far:
public function graphheheByDate(Request $request, $companyID)
{
$companyID = $this->decode($companyID);
$match = DiraChatLog::where('status','=','Match')->where('date_access', '>=', $request->from)->where('date_access', '<=', $request->to)
->selectRaw('DATE(date_access) as date, COUNT(1) as cnt') // created_at here is datetime format, only need the date portion using `DATE` function
->orderBy("date")
->groupBy("date")
->get() // return result set (collection) from query builder
->pluck('cnt') // only need the cnt column
->values() // array_values
->sum(); // convert collection to array
$missing = DiraChatLog::where('status','=','Missing')->where('date_access', '>=', $request->from)->where('date_access', '<=', $request->to)
->selectRaw('DATE(date_access) as date, COUNT(1) as cnt') // created_at here is datetime format, only need the date portion using `DATE` function
->orderBy("date")
->groupBy("date")
->get() // return result set (collection) from query builder
->pluck('cnt') // only need the cnt column
->values() // array_values
->sum(); // convert collection to array
$noAnswer = DiraChatLog::where('status','=','No Answer')->where('date_access', '>=', $request->from)->where('date_access', '<=', $request->to)
->selectRaw('DATE(date_access) as date, COUNT(1) as cnt') // created_at here is datetime format, only need the date portion using `DATE` function
->orderBy("date")
->groupBy("date")
->get() // return result set (collection) from query builder
->pluck('cnt') // only need the cnt column
->values() // array_values
->sum(); // convert collection to array
$match = array(0 => $match);
$missing = array(0 => $missing);
$noAnswer = array(0 => $noAnswer);
// dd($match,$missing,$noAnswer);
$from = $request->from;
$to = $request->to;
// dd($from, $to);
$companyID = $this->encodeID($companyID);
return view('AltHr.Chatbot.graphhehe', compact('companyID','from','to'))->with('match',json_encode($match,JSON_NUMERIC_CHECK))->with('missing',json_encode($missing,JSON_NUMERIC_CHECK))->with('noAnswer',json_encode($noAnswer,JSON_NUMERIC_CHECK));
}
in this function when i dd the 3 values are correct details. i only want this data to bring to the same page to change the graph.
my graph javascript is as below:
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script type="text/javascript">
var match = <?php echo $match; ?>;
var missing = <?php echo $missing; ?>;
var noAnswer = <?php echo $noAnswer; ?>;
Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: 'Unique Visitors'
},
subtitle: {
text: ''
},
xAxis: {
categories: [
'Dates'
],
crosshair: true
},
yAxis: {
min: 0,
title: {
text: 'Total'
}
},
credits: {
enabled: false
},
exporting: {
enabled: false
},
tooltip: {
headerFormat: '<span>{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y}</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Match',
data: [match]
}, {
name: 'Missing',
data: [missing]
}, {
name: 'No Answer',
data: [noAnswer]
}]
});
</script>

mapping join results as an array under related rows

In laravel am using eloquent to get data from the database.
I have two tables 'questions' and 'options'
Am using the eloquent method to join 'options' to 'questions'
$questions = Question::join('options', 'options.question_id', 'questions.id');
return QuestionResource($questions);
This does return an expected collection of data, where the same question appear multiple times in the collection and each is joined with different options where the 'options.question_id' and 'question.id' are the same.
[
{
id: 1,
text: "Africa is a...?",
// joined option
question_id: 1,
value: "city",
answer: false
},
{
id: 1,
text: "Africa is a...?",
// joined option
question_id: 1,
value: "planet",
answer: false
},
{
id: 1,
text: "Africa is a...?",
// joined option
question_id: 1,
value: "continent",
answer: true
},
{
id: 2,
text: "Albert Heinstein was a...?",
// joined option
question_id: 2,
value: "comedian",
answer: false
},
{
id: 2,
text: "Albert Heinstein was a...?",
// joined option
question_id: 1,
value: "genius scientist",
answer: true
}
]
I want all options be nested under a key within the related question. Like
[
{
id: 1,
text: "Africa is a...?",
// joined options
options: [
{value: "city", answer: false},
{value: "planet", answer: false},
{value: "continent", answer: true}
]
},
{
id: 2,
text: "Albert Heinstein was a...?",
// joined options
options: [
{value: "comedian", answer: false},
{value: "genius scientist", answer: true}
]
}
]
Can I achieve this with laravel's eloquent or I'll have to apply an extra logic.
If you want to applie extra logic this code may help you
<?php
$combinedqst = array('id' => '','text'=> '','option'=> array('value' => array('value' => ,'' ), 'answer' => ''));
$ids = array('id' => , '');
//loop through questions array 1st loop for getting the question
foreach($questions as $question) {
$count = 0;
//check if question is already looped
if(!in_array($question["id"],$ids)){
//2end loop to get the opstions
foreach($questions as $question_check) {
if($question_check["id"] == $question["id"]){
if($count == 0){
$combinedqst["id"] = $question["id"];
$combinedqst["text"] = $question["text"];
}
$count = 1;
array_push($combinedqst["option"]['value'],$question_check['value']);
array_push($combinedqst["option"]['answer'],$question_check['answer']);
}
}
}
array_push($ids,$question["id"]);
}
vardump($combinedqst);

Create flot on PHP data

I would like to create a flot bar graph based on a php output. I managed to output data from php, but I would also like to use labels and display them on the xaxis. For some reason the output of the code below is invalid. The labels show up, but the bars and xaxis labels do not.
PHP:
function getOverview() {
$arr[] = array(
'label' => "Label 1",
'data' => array(0, 1)
);
$arr[] = array(
'label' => "Label 2",
'data' => array(1, 2)
);
echo json_encode($arr);
}
Output:
[{"label":"Label 1","data":[0,1]},{"label":"Label 2","data":[1,2]}]
jQuery:
$(document).ready(function(){
$.ajax({
url: 'http://localhost/getOverview.php',
method: 'GET',
dataType:"json",
success: onOutboundReveived
});
function onOutboundReveived(series)
{
var options = {
series: {
bars: {
show: true,
barWidth: .1,
align: 'center'
}
},
xaxis: {
tickSize: 1
}
};
$.plot("#chart_filled_blue", series, options);
}
});
Can anyone help me?
You've got a couple problems:
1.) Series data needs to be an array of arrays. Not just a single array:
'data' => array(array(1, 2))
This is, of course, so a series could have more than one point (even though your's has a single point).
2.) To get xaxis labels, you have two options. One, use the categories plugin. Two, manually provide the tick labels:
ticks: [[0, "zero"], [1.2, "one mark"], [2.4, "two marks"]]
In your situation I'd just use the category plugin. You'll need to modify the final data to:
{"label":"Label 1","data":[["Label 1",1]]}
or in the PHP:
$arr[] = array(
'label' => "Label 1",
'data' => array(array("Label 1", 1))
);
Here's a fiddle.
I think, your output has an incorrect format. Try this:
[
{
label: "Label 1",
data: [[0,1]]
},
{
label: "Label 2",
data: [[1,2]]
}
]

Categories