Here is my array fetched from database. I need to that array data fill into google data chart. I tried few ways but I couldn't do that. please some one help me to do that.
code// dd($dates);
here dataTable.addRows section I need to replace, 1st picture displaying dataList.
please help me.
viewerController.php
public function show(){
$dates = collect();
foreach( range( -6, 0 ) AS $i ) {
$date = Carbon::now()->addDays( $i )->format( 'Y-m-d' );
$dates->put( $date, 0);
}
// Get the post counts
$persons = Person::where( 'created_at', '>=', $dates->keys()->first() )
->groupBy( 'date' )
->orderBy( 'date' )
->get( [
DB::raw( 'DATE( created_at ) as date' ),
DB::raw( 'COUNT( * ) as "count"' )
] )
->pluck( 'count', 'date' );
// Merge the two collections; any results in `$posts` will overwrite the zero-value in `$dates`
$dates = $dates->merge( $persons );
return view('layouts.chart',compact(['dates']));
}
Related
for a wordpress-based real estate ad client site I have developed a system for sending advertisements via e-mail to subscribed clients.
To avoid sending the same advertisement several times, I have created a flag system that highlights whether the advertisement has already been sent or not.
To register the advertisements sent, I use the ID and in a specific column I go to register the IDs of the advertisements selected with a checkbox, the data is transferred through a javascript function.
Here the jquery section code:
var checkboxVals = $('.listing_multi_id'); // This for id of post(advert) checked
var email_to = $('#lead_email').val(); // This tell me the email to send.
var lead_id = $('#lead_id').val(); // This tell me the col ID in DB of my client
var already_ID = $('#annunci_inviati').val(); //This tells me which ids are already present in the database row as sent
var vals = $('.listing_multi_id:checked').map(function() {return this.value;}).get().join(',') // This create array of ids of post(advert) checked
// And all information is sent through json post
$.ajax({
type: 'POST',
dataType: 'json',
url: ajaxurl,
data: {
'action': 'houzez_match_listing_email',
'ids': vals,
'email_to': email_to,
'id_lead': lead_id,
'already_inviati': already_ID,
},''''
Here the php section code:
// I have omitted all the information that does not concern the question, the function I am using is much more complex and structured than the one you see
$listing_ids = sanitize_text_field($_REQUEST['ids']); // Array with the ids of post
$already_inviati1 = sanitize_text_field($_REQUEST['already_inviati']); // Array with the ids of post already sent
// Here transform the array in array with INT ids
$strings_array = explode(',', $already_inviati1);
foreach ($strings_array as $each_number=>$id) {
$already_inviati2[] = $id;
}
// up to here
// Here check if the is the first sent or not
if (isset($already_inviati1)) {
$merged = array_merge($already_inviati2,$listing_ids);
$annunci_inviati = maybe_serialize($merged);
} else
{$annunci_inviati = maybe_serialize($listing_ids);}
// Here save the value in database
$id_cliente = $_POST['id_lead'];
$data_table= $wpdb->prefix . 'crm_enquiries';
$data = array(
'annunci_inviati' => $annunci_inviati
);
$format = array(
'%s'
);
$where = array(
'lead_id' => $id_cliente
);
$where_format = array(
'%d'
);
$wpdb->update( $data_table, $data, $where, $format, $where_format );
// FINE SCRIPT
As you can see, the script works if it is the first sending of the mails, so if the column is empty.
On the second send, it goes into error, the array is merged but when I go to check its value it becomes this:
// I use a hidden input in html to check ids already sent
<input type="hidden" id="annunci_inviati" value="array (
0 => 0, // Old IDs are lost by becoming numbers
1 => 1, // Old IDs are lost by becoming number
2 => 2, // Old IDs are lost by becoming number
3 => 0, // Old IDs are lost by becoming number
4 => 53161, // the new id selected
5 => 53153, // the new id selected
6 => 53144, // the new id selected
)">
How can I solve?
You are trying to merge a string with an array. Try the below which ensures the input values are correctly converted to arrays.
/**
* #var array Array of listing ID's.
*/
$listing_ids = !empty( $_REQUEST[ 'ids' ] ) ? array_map( 'intval', explode( ',', $_REQUEST[ 'ids' ] ) ) : [];
/**
* #var array Array of ID's for post already sent.
*/
$already_sent = !empty( $_REQUEST[ 'already_inviati' ] ) ? array_map( 'intval', explode( ',', $_REQUEST[ 'already_inviati' ] ) ) : [];
/**
* #var array Merge the listing ID's and already sent ID's for storing.
*/
$merged = array_unique( array_merge( $listing_ids, $already_sent ) );
/**
* #var int|null The client record to update.
*/
$id_cliente = !empty( $_POST[ 'id_lead' ] ) ? (int)$_POST[ 'id_lead' ] : null;
if ( $id_cliente ) {
$data_table = $wpdb->prefix . 'crm_enquiries';
$wpdb->update( $data_table, [
'annunci_inviati' => maybe_serialize( $merged )
], [
'lead_id' => $id_cliente
], [
'%s'
], [
'%d'
] );
}
I am creating a table using datatables and I am having some trouble rendering data in it. My Table structures are.
TABLE_1
|------|------|-------|
| ID | NAME | PHONE |
|------|------|-------|
TABLE_2
|------|------------|----------|
| ID | TABLE_1_ID | CATEGORY |
|------|------------|----------|
This is my PHP code
$db = new Database; // Database connection
$sql = "SELECT a.*, b.* FROM TABLE_1 a, TABLE_2 b WHERE a.ID = b.TABLE_1_ID";
$exe = $db->select($sql);
$result = array();
foreach ($exe as $rows) {
$result[] = $rows;
}
echo json_encode($result);
This is my JavaScript
$('#example').DataTable({
ajax: {
url:"data.php",
dataSrc:""
},
columns: [
{data:"NAME"},
{data:"CATEGORY"}
]
});
Up to this point everything is working fine, the data is perfectly loaded. But the problem is, suppose I have only one row in TABLE_1 and 5 rows in TABLE_2 where TABLE_1.ID = TABLE_2.TABLE_1_ID and bcoz of this my datatable is generating 5 rows but I want all the categories in a single cell and I want only one row instead of 5.
I am thinking of doing some stuff inside the render function, like
$('#example').DataTable({
ajax: {
url:"data.php",
dataSrc:""
},
columns: [
{data:"NAME"},
{
data:"ID",
render: function(data, type, row){
// Some stuff to render 5 Category in a single cell
// Using the ID from row.ID (maybe)
// how to return 5 CATEGORY in this cell
}
}
]
});
But I really don't know the process and google + stackoverflow + datatables forum is little bit confusing for me bcoz I am not good in Javascript.
Can you guys help me achieve this? What type of code or what code I have to write inside the render finction to display 5 CATEGORY in a single cell.
Thanks in advance.
You can transform your data in your application layer so that in resultant array you will have only rows for table a along with related category names.
First you need an ordered result set like
select a.id,
a.phone,
a.name,
b.category
from table_1 a
join table_2 b
on a.id = b.table_1_id
order by a.id asc
Then loop through all records and cook your data set
$result = [];
$currentParent = false;
$data = null;
foreach ($rows as $row) {
/*
* if id is changed then its a different record
* prepare data for new row and create a comma separated string of category names
*/
if ($currentParent != $row['id']) {
if($data != null){ // for first and intermediate rows
$result[]= $data;
}
$data = ['name'=> $row['name'], 'category'=> ''];
$currentParent = $row['id'];
}
$data['category'] = empty($data['category']) ? $row['category']: $data['category'] .", ". $row['category'];
}
$result[]= $data; // add data for last row
echo json_encode($result);
The resultant array would look like
Array
(
[0] => Array
(
[name] => item 1
[category] => Cat 1, Cat 2, Cat3
)
[1] => Array
(
[name] => item 2
[category] => Cat 1, Cat 2, Cat3
)
[2] => Array
(
[name] => item 3
[category] => Cat 1, Cat 2, Cat3
)
)
Another shorthand way but not preferred is to apply aggregate methods on query level like if you are using MySQL you can use group_concat but it has a restriction of max character limit (which is adjustable).
I´m having trouble using FullCalendar v3.8.2 and the eventDataTransform Method.
I´m searching for hours now, so to prevent going crazy I write my first StackOverflow post...
I want pass an additonal parameter to the event Object, calles blockd. So in frontent the events which are blocked get a different styling
If I pass the blocked parameter with Int 1, the events of the calendar show up in the frontend. ( As shown in code ex below )
Though I do a PHP variable e.g. $is_blocked instead, I get a TypeError in frontend and the events dont show up.
Thats my fullcalendar.js script:
eventSources: [
{
url: WP_PUBLIC_DATA.pluginsUrl + '/dev-booking-system/dbs-calendar-feed.php', // use the `url` property
className: 'dbs-event',
eventDataTransform: function( eventData ){
var blocked = parseInt( eventData.blocked );
if( blocked == 1 ){
var substr = 'Reserviert - ' + eventData.title.substring( 0, 15 ) + '...';
return {
id: eventData.id,
title: substr,
start: eventData.start,
end: eventData.end,
className: 'dbs-event--disabled-by-load'
};
}
}
}
],
When sending a JSON to javascript file, something weird happens.
eventSoruces url gets data from php file with a wordpress loop.
That's the point where it gets weird. Passing 'blocked' => 1 works, passing 'blocked' => $is_blocked dont work (value is converted to int via intval)
if( $event_listing->have_posts() ) :
while( $event_listing->have_posts() ) : $event_listing->the_post();
$post_id = get_the_ID();
$title = get_the_title();
$is_blocked = intval( get_post_meta( $post_id, 'event_reserved', true ) );
$start = get_post_meta( $post_id, 'start_trip', true ) != '' ? get_post_meta( $post_id, 'start_trip', true ) : NULL;
$end = get_post_meta( $post_id, 'end_trip', true ) != '' ? get_post_meta( $post_id, 'end_trip', true ) : NULL;
$event_array[] = array(
'id' => $post_id,
'title' => $title,
'start' => $start,
'end' => $end,
// 'blocked' => 1,
'blocked' => $is_blocked,
'allDay' => true // Event ist nicht Zeitabhängig
);
endwhile;
else:
wp_send_json_error( "No events found" );
endif;
echo json_encode($event_array);
exit;
Using Wordpress, i enqueue the scripts in correct order:
//fullcalendar
wp_enqueue_script('dbs-fullcalendar-moment-scripts', plugins_url('assets/fullcalendar/lib/moment.min.js', __FILE__ ), array('jquery'), '3.8.2', true );
wp_enqueue_script('dbs-fullcalendar-scripts', plugins_url('assets/fullcalendar/fullcalendar.js', __FILE__ ) , array('jquery'), '3.8.2', true );
Firefox says TypeError: eventInput is undefined, Chrome against says Uncaught TypeError: Cannot read property 'start' of undefined
Do you have any idea whats going on ?
Would be great hearing from your, stop me for drinking too much coffee ;)
Here is the JSON Result:
0:
id: 3453
title: "19. März bis 23. März Beipieltext"
start: "2018-03-19"
end: "2018-03-23"
blocked: 0
allDay: true
1:
id: 3451
title: "09. März bis 11. März Beispieltext"
start: "2018-03-09"
end: "2018-03-11"
blocked: 1
allDay: true
The 'blocked' value recieved as an int value, but it seems javascript has a problem with the '0', because transfering only '1' values as explained above, the whole thing works
The problem is that whenever blocked is 0, your eventDataTransform method does not return anything to the calendar, so the code which tries to use the returned event is crashing because it's trying to access an event object which doesn't exist.
Even if you're not going to change the event data, you still need to just return the existing event data back again.
You also don't need to do parseInt() since blocked is already a number, and you don't really need to build a new event object - you can just modify the one given to you. So your code can be as follows:
eventDataTransform: function( eventData ){
if( eventData.blocked == 1 ){
var substr = 'Reserviert - ' + eventData.title.substring( 0, 15 ) + '...';
eventData.title = substr;
eventData.className = 'dbs-event--disabled-by-load';
}
return eventData; //always return something, even if it wasn't modified
}
My aim is to create multiple line charts on the same graph using data i pull from mysql database.
I have the code in place but I'm missing a step therefore not getting the output I expect. Here's my code:
<?php
$results = array('cols' => array (array('label' => 'Date', 'type' => date'),
array('label' => 'Amount', 'type' => 'number')
),
'rows' => array()
);
$query = $db->prepare('SELECT * FROM Claims GROUP BY EXTRACT(MONTH FROM ClaimDate ) , EXTRACT( YEAR FROM ClaimDate ) ');
$query->execute();
$rows1 = $query->fetchAll(PDO::FETCH_ASSOC);
foreach($rows1 as $row)
{
$ClaimDate = DateTime::createFromFormat('Y-m-d H:i:s', $row['ClaimDate'])->format('Y-m-d');
$dateArr = explode('-', $ClaimDate);
$year = (int) $dateArr[0];
$month = (int) $dateArr[1] - 1;
$day = (int) $dateArr[2];
$results['rows'][] = array('c' => array(array('v' => "Date($year, $month, $day)"), array('v' => $row['amount'])
));
}
$json = json_encode($results, JSON_NUMERIC_CHECK);
// print_r($json);exit;
?>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart()
{
var data = new google.visualization.DataTable(<?php echo json_encode($json); ?>);
var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
chart.draw(data, {width: 400, height: 240});
}
</script>
<div id="line_chart"></div>
So that's my code. This is the json that is passed to the chart from the database:
{"cols":[{"label":"Date","type":"date"},{"label":"Amount","type":"number"}],"rows":[{"c":[{"v":"Date(2015, 5, 23)"},{"v":6000}]},{"c":[{"v":"Date(2016, 5, 23)"},{"v":16000}]},{"c":[{"v":"Date(2015, 6, 23)"},{"v":10000}]},{"c":[{"v":"Date(2016, 6, 23)"},{"v":10000}]},{"c":[{"v":"Date(2015, 7, 23)"},{"v":5000}]},{"c":[{"v":"Date(2016, 7, 23)"},{"v":60000}]}]}
And below is the line chart that is output:
line chart output from above code
This is not what I want. My end goal is to get graph that displays multiple line charts(depending on the number of years present) with all the months displaying on the X-axis with the amount displaying on the Y-axis. This is the closest thing I've seen that resembles what I want to achieve:
linechart
The above image shows what I want to achieve. Like stated before, the months on the X-axis with the amount on the Y-axis. then the 'values' would be the years that have been returned from the query i.e. every year will have its own line chart
I'm a bit stuck on this and would like to request for guidance on how to accomplish this
Additional request
SIDU has tried to provide assistance by recommending I use the svg charts. Appreciated but can't this be done using google charts?
This would be easy with Topnew SVG Charts:
http://topnew.net/cms/cms_chart.php?data=ymd,Hit,IP;2016-01-01,2000,1000;2016-02-05,3000,1800;2016-03-20,4000,3000&chart=line&fmt=str_xss&xFormat=date|M
If you download the 9k topnew svg chart, you can call it in the following way instead:
<?php
include 'topnew_svg_chart.php';
$data = [
'Hit' => [
'2016-01-01' => 12345,
'2016-02-03' => 12345,
],
'IP' => [
'2016-01-01' => 2345,
'2016-02-03' => 2345,
]
];
$init = [
'chart' => 'line',
'xFormat' => 'date|M',
];
cms_chart($data, $init);
Though this is a textbook problem, but I'm not able to parse from json object. I have a json object coming from a page, and I need to extract the ID,fieldText value so that I can update the table.
Here is how I'm capturing the json and converting it into array, not sure how to extract the values.
if(isset($_POST['postData'])){
$json = json_decode($_POST['postData'],true);
foreach ($json as $key => $value)
{
print_r($key);
//print_r($value);
foreach ($value as $k => $val)
{
//echo "$k | $val <br />";
} }
I need to update the table with [ID] and [fieldText] :
Result should like this::(1:Hello World), (2:The rising Star),(3: Terminator)
My JSON object is like this:
Array(
[fieldName] => Array
(
[0] => fieldText[1]
[1] => fieldText[2]
[2] => fieldText[3]
)
[fieldText] => Array
(
[0] => HelloWorld
[1] => The rising Star
[2] => Terminator
)
[ID] => Array
(
[0] => 1
[1] => 2
[2] => 3
))
Hi it seems that there are three arrays in your JSON, I think it would be better to change the way you generate the JSON to make it simple to understand.
// assumes $arr as the $_POST['postData'] in your case
$arr = array("1"=>"Hello World", "2"=>"The Rising Star", "3"=>"Terminator");
$j = json_encode($arr);
$json = json_decode($j,true);
foreach ($json as $key => $value)
{
echo '('.$key.','. $value.')';
}
The results are :
(1,Hello World)(2,The Rising Star)(3,Terminator)
Hope this can help you.
Hope you can do something like this.
$jsonData = Array(
'Name' => Array
(
0 => 'Text1',
1 => 'Text2',
2 => 'Text3'
),
'Value' => Array
(
0 => 'HelloWorld',
1 => 'The rising Star',
2 => 'Terminator'
),
'ID' => Array
(
0 => 1,
1 => 2,
2 => 3
)
);
$length = count($jsonData['ID']);
for($j=0;$j<$length;$j++) {
echo "(".$jsonData['ID'][$j].": ".$jsonData['Value'][$j].")<br/>";
}
In my opinion you should make your life easier by modifying the json array you receive with $_POST['data'];. If I were in your shoes my json would've been exactly as you need it:
{ 1:'Hello World', 2:'The rising Star',3:'Terminator' }
But if you are not able to change it for any reason I think you could use something like this (basing this example on your code):
$jsonData = json_encode($_POST['json'], true);
$id = $jsonData['ID'];
$fieldText = $jsonData['fieldText'];
$arr = array();
for ($i=0; $i < count($id); $i++) {
$arr[(int) $id[$i]] = $fieldText[$i];
}
var_dump($arr);
Hope this helps you!