Could someone please tell me how to structure my php array so that i can plug it straight into the Google pie chart API? Here is my current code:
PHP:
// class containing sql
$browser_data = browser_data();
// array to populate titles
$data_array['titles'] = array('title', 'amount');
//array to populate data
foreach($browser_data as $k=>$val) {
$data_array[$k] = array($k, $val['examples']);
}
JS:
data_array = <?=json_encode($data_array)?>;
var data = google.visualization.arrayToDataTable(data_array);
You need to remove 'titles' and '$k' from the array keys, as json_encode will create an object from an associative array instead of an array. This is what you need:
// array to populate titles
$data_array[] = array('title', 'amount');
// array to populate data
foreach($browser_data as $k=>$val) {
$data_array[] = array($k, $val['examples']);
}
If your data source outputs numbers as strings (some databases, including MySQL, do this), you need to add JSON_NUMERIC_CHECK to the json_encode call:
data_array = <?=json_encode($data_array, JSON_NUMERIC_CHECK)?>;
Related
i have code above which gets data from a database and then place in in json form to make it readable in java script.
the results of the echo is
"FIAT":["Anglia","Bronco","Capri","Cobra","Consul","Corsair","Cortina"],
"Land Rover":["Defender","Discovery","Discovery 3","Discovery 4"]
I would like the data to be converted in such a way the i can reference it in this form Var Brand=array ();
Brand["FIAT"]=["Anglia","Bronco","Capri","Cobra","Consul","Corsair","Cortina"];
Brand["Land Rover"]=["Defender","Discovery","Discovery 3","Discovery 4"];
in java script. Does Any one know how i can do this.
$query = mysqli_query($conn,"SELECT * FROM car_models");
// Loop the DB result
while(($result = mysqli_fetch_array($query))) {
// Check if this ID is already in the data array
if(!array_key_exists($result['Brand'], $data)){
// Create array for current user
$data[$result['Brand']] = array();
}
// Add the current race time to the array (do not need to use the float)
$data[$result['Brand']][] = $result['Model'];
}
//json data
json_encode($data);
I found the solution. Simply added the json object in a variable and now am able to get the echo it to the console
`
//json data
var brandAvailable =
console.log(brandAvailable);
"`
I want to extract Lat/Long values from the below mentioned array. Please help me.
var products = {"PolygonCords":"[[51.65040675460229,0.034332275390625],[51.613752957501,0.028839111328125],[51.61034179610213,0.1812744140625],[51.642737480428536,0.157928466796875]]"};
Parse the json string using JSON.parse() and iterate over array using forEach
var products = {
"PolygonCords": "[[51.65040675460229,0.034332275390625],[51.613752957501,0.028839111328125],[51.61034179610213,0.1812744140625],[51.642737480428536,0.157928466796875]]"
};
JSON.parse(products.PolygonCords).forEach(function(v) {
console.log(v[0], v[1])
})
I'm building an application with Laravel which communicates with an OpenCPU server to perform some calculations. The OpenCPU server returns data in JSON format, which I then process to pull out the relevant information. This data returns a sku, retailer, date and sales. These are then posted to a controller using AJAX. Within this controller I then want to upload this data into the database by creating a new array of data to upload in one go. Each row should have a sku, retailer, date and sales. The date field in the database is called date, but called obs in the code.
OpenCPU returns JSON which is the parsed to a Javascript object using
var data = JSON.parse(output);
After logging to the Javascript console I get an array of the correct length, with the sales numbers.
The data is then sent to a Laravel controller via AJAX
$('#save').click(function(){
var id = $('#filter option:selected').text();
var json = $.ajax({
url: 'sales/' + id + '/update',
type: 'POST',
data: {
'sku': $('#sku').text(),
'retailer': $('#retailer').text(),
'obs': data.OBS,
'sales': data.Sales,
},
async: false
}).responseText;
var message = JSON.parse(json);
$('.flash').html(message).fadeIn(300).delay(2500).fadeOut(300);
});
In Laravel I then try to store the data in a MySQL database using the following
$sku = Input::get('sku');
$retailer = Input::get('retailer');
$obs = Input::get('obs');
$sales = Input::get('sales');
foreach($obs as $key => $n ){
$arrayData[] = array(
'sku' => $sku,
'retailer' => $retailer,
'date' => $obs[$key]
'sales' => $sales[$key]
);
}
Chart::create($arrayData);
However the above code doesn't appear to work. The following code will create the correct number of rows in the database with the sku and retailer populated, but the sales figure is just the loop number, rather than the number of sales
$sku = Input::get('sku');
$retailer = Input::get('retailer');
$dates = Input::get('obs');
$sales= Input::get('sales');
foreach(range(1, count($dates)) as $key){
DB::table('charts')->insert(
[
'sku' => $sku,
'retailer' => $retailer,
'date' => DateTime($obs[$key]),
'sales' => $sales[$key]
]
);
}
Given that the sku and retailer are a single input and repeated, I expect it's either an issue with passing the array to Laravel or the way in which I'm trying to access the elements in the 'obs' and 'sales' array
It looks like you have the right steps, get the inputs:
$sku = Input::get('sku');
$retailer = Input::get('retailer');
$dates = Input::get('obs');
$sales= Input::get('sales');
Buy now you try to forcibly insert them into the database. Why not use eloquent for database insertion: (Keep in mind you'd need to have a model for the charts table called Chart.php)
$chart = new Chart;
$chart->sku = $sku;
$chart->retailer = $retailer;
$chart->dates = $dates;
$chart->save();
That being said, I do realize that you're trying to pass arrays to the database, so that might take some experimentation. If you can't figure out what's (attempting) being passed to the database, you can always use:
die($variable);
To check what's up. Good luck!
I need to store values into a Wordpress database and the use the value in a Google Chart.
The questions are:
1. What format do I use to store it into the database?
Currently I am using WP-TYPES and adding the array as follows to a Multi Line Box:
['Month','Value 1','Value 2'],['2004',1000,400],['2005',1170,460],['2006',660,1120],['2007',1030,540]
This is what it needs to output in the Javascript for the chart.
Convert the String to a array in PHP (Not doing it correctly)
I retrieve the data with:
$graphdata = types_render_field("graph-data", array("output" => "raw","separator"=>";"));
This gives me a string value.
Then I add it to an array:
$thechartcontent[$i] = [
"name" => get_the_title(),
"chartheaders" => array($graphdata),
];
In JavaScipt:
I set the PHP Array to Java
var chart1 = <?php echo json_encode($thechartcontent[0]); ?>;
Then I get the data from the array to a var:
var chartheaders1 = chart1['chartheaders'];
This is where I get stuck. The value that I get is a string. It needs to show exactly this:
['Month','Value 1','Value 2'],['2004',1000,400],['2005',1170,460],['2006',660,1120],['2007',1030,540]
for it to work.
Any help please.
Well, it will not be exacly like you want since it's JSON encoded in JSON format. This might be useful. Or you can convert object into array in JS.
I suspect that what you are outputting is an array containing a string, which is not what you want. You must split $graphdata into an array of arrays containing your data before adding it to $thechartcontent:
$graphdata = substr($graphdata, 1, strlen($graphdata) - 1); // trim the opening and closing brackets
$graphdata = explode('],[', $graphdata); // split $graphdata into an array of strings
foreach($graphdata as &$row) {
$row = explode(',', $row); // split the row into an array
}
$thechartcontent[$i] = array(
'name' => get_the_title(),
'chartheaders' => $graphdata
);
When you json encode the data, you should use the JSON_NUMERIC_CHECK constant, so your numbers don't get quoted as strings:
var chart1 = <?php echo json_encode($thechartcontent[0], JSON_NUMERIC_CHECK); ?>;
I have a JSON which lists the values from database. Below is the JSON data of 2 rows from the database.
[{"Name":"P1","Description":"pd1","Value":"v1","Attribute":"a1"},{"Name":"P1","Description":"pd1","Value":"v2","Attribute":"a2"}]
database values are the result of a left join query. Only 'Value' and 'Attribute' fields are different. Can I append that fields to JSON instead of multiple sets of record? I know there is 'push' to do this, but I am unaware where and how to use this in my code. below is the code for fetching values from db and serializing the values.
GetProfileDataService GetProfileDataService = new BokingEngine.MasterDataService.GetProfileDataService();
IEnumerable<ProfileData> ProfileDetails = GetProfileDataService.GetList(new ProfileSearchCriteria { Name = strProfileName });
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string strSerProfileDetails = javaScriptSerializer.Serialize(ProfileDetails);
context.Response.ContentType = "text/json";
context.Response.Write(strSerProfileDetails);
Below is my getJSON
$(document).ready(function () {
$.getJSON('ProfileHandler.ashx', { 'ProfileName': 'Profile 1' }, function (data) {
$.each(data, function (k, v) {
alert(v.Attribute+' : '+v.Value);
});
});
});
Please help me here.
There are several things you can do.
Store value and attribute as arrays:
[{"Name":"P1","Description":"pd1","Value":["v1", "v2"],"Attribute":["a1", "a2"]}]
Or store them as a 'symbol'-separated string:
[{"Name":"P1","Description":"pd1","Value":"v1;v2"],"Attribute":"a1;a2"]}]
In order to use the first case, you'll have to try and figure out how to format the ProfileDetails in order to have javaScriptSerializer.Serialize parse it correctly. You will likely have to convert your data first in order for this to work (i.e. convert value and attribute to arrays).
For the second case to work you could modify your GetProfileDataService.GetList method so that values and attributes are merged to symbol-separated strings (something like this: GROUP BY to combine/concat a column)