I am trying to add multiple events to codeigniter calendar. I have found solution for that already. The problem I am facing is that, for multiple events on same day I want array like this
$data = array(
1 => 'class1',
3 => array('class2', 'class3'),
4 => 'class4'
);
Here is my model function and mysql query
public function getClasses($year,$month)
{
$this->db->like('date_from', $year."-".$month, 'after');
$query = $this->db->get('classes');
$data = array();
foreach($query->result() as $row)
{
$data[(int)substr($row->date_from, 8, 2)] = $row->class_name;
}
return $data;
}
date_from is in this format 2015-02-25
Right now the function make single array for example
$events = array(
1 => 'class1',
4 => 'class4'
);
But I want it to make nested array. How this can be solved?
Related
I am trying to merge two results of two queries in MYSQL using PHP, but I am puzzled how to do it! I am using PDO. I am programming for a hobby and am trying to make a to do list app just like a Trello board. However, I just can't figure out how to merge two results from different tables in a database.
The idea is as follows:
I have a table called 'task_lists' with the content:
'list_id => 1, list_name = 'listOne'
'list_id => 2, list_name = 'listTwo'
And a table called 'tasks':
task_id => 1, list_id => 1, task_name => 'taskOfListOne', duration => 5, is_done => 1
task_id => 2, list_id => 1, task_name => 'anotherTaskOfListOne', duration => 5, is_done => 1
task_id => 3, list_id => 2, task_name => 'taskOfListTwo', duration => 10, is_done => 0
And I am trying to create an array that is merged between the two results as something like:
(I know this is a rough picture of how the array is supposed to look like)
$result = [array]
[list_id] = 1, [list_name] = 'listOne' =>
[array][list_id] = 1, ['task_name] = taskOfListOne,[duration] = 5, ['is_done'] => 1
[array][list_id] = 1, ['task_name] = anotherTaskOfListOne,[duration] = 5, ['is_done'] => 1
[list_id] = 2, [list_name] = 'listTwo' =>
[array][list_id] = 2, ['task_name] = taskOfListTwo,[duration] = 5, ['is_done'] => 1
Is this even possible? I have tried a Union sql query and methods like nested foreach statements, but none of them worked for me. Am I missing something here?
PS: Sorry for my bad english.
Have you tried a left join?
SELECT TL.`list_id`, TL.`list_name`, T.`task_name`, T.`duration`
FROM task_lists AS TL
LEFT JOIN tasks as T ON TL.`list_id` = T.`list_id`
And then in PHP you build the array in the format you want.
Later edit:
Simple PHP example to parse SQL data as you asked (to remove duplicated info):
<?php
// $mysql_rows -> here is your query result, fetched as associative array
$filtered_array = array();
foreach ($mysql_rows as $row){
// Initiate record if is not already initiated
if (!isset($filtered_array[ $row['list_id'] ])){
$filtered_array[ $row['list_id'] ] = array(
'list_id' => $row['list_id'],
'list_name' => $row['list_name'],
'tasks' => array()
);
}
// Add tasks
$filtered_array[ $row['list_id'] ]['tasks'][] = array(
'task_name' => $row['task_name'],
'duration' => $row['duration'],
'is_done ' => $row['is_done ']
);
}
// Optional: if you want to remove list_id from $filtered_array key names, uncomment the next line
// $filtered_array = array_values($filtered_array);
?>
I am getting an error while inserting into my database.
Its showing column ARRAY. How to fix it? Instead of that I want to pass all dates (showing in the screenshot only dates in the date column)
I want to know in code where I did mistake. Why the array is coming like this?
PHP MODAL
$data_jobschedule = array(
'jobschedule_id' => $jobschedule_id,
'Activity_area_id' => $Activity_area_id,
'Contract_id' => $this->input->post('getcontract_id'),
'job_freq_id' => $this->input->post('getcontractbranch_freq'),
'job_schedule_dates' => $this->input->post('getschedule'),
//'job_schedule_frequency' => $this->input->post('getjob_schedule_frequency'),
'created_at' =>$created_Dt
);
$insert_id = 0;
if ($this->db->insert("activity_area", $data)) { //AM INSERTING ANOTHER RECORD ALSO TO DIFFERENT TABLE
$this->db->insert('job_schedule', $data_jobschedule); //HERE IS THE TABLE I NEED TO ADD DATES AND FREQUENCY
$insert_id = $this->db->insert_id();
}
so your post data is an array, you need looping through it.
on your php model, try change this
$data_jobschedule = array(
'jobschedule_id' => $jobschedule_id,
'Activity_area_id' => $Activity_area_id,
'Contract_id' => $this->input->post('getcontract_id'),
'job_freq_id' => $this->input->post('getcontractbranch_freq'),
'job_schedule_dates' => $this->input->post('getschedule'),
//'job_schedule_frequency' => $this->input->post('getjob_schedule_frequency'),
'created_at' =>$created_Dt
);
$insert_id = 0;
if ($this->db->insert("activity_area", $data)) { //AM INSERTING ANOTHER RECORD ALSO TO DIFFERENT TABLE
$this->db->insert('job_schedule', $data_jobschedule); //HERE IS THE TABLE I NEED TO ADD DATES AND FREQUENCY
$insert_id = $this->db->insert_id();
}
to
$insert_id = 0;
if ($this->db->insert("activity_area", $data)) { //AM INSERTING ANOTHER RECORD ALSO TO DIFFERENT TABLE
if (is_array($this->input->post('getschedule'))) {
foreach($this->input->post('getschedule') as $value) {
$this->db->insert('job_schedule', array(
'jobschedule_id' => $jobschedule_id,
'Activity_area_id' => $Activity_area_id,
'Contract_id' => $this->input->post('getcontract_id'),
'job_freq_id' => $this->input->post('getcontractbranch_freq'),
'job_schedule_dates' => $value[0], //assume array form like your screenshot
'job_schedule_frequency' => $value[1],
'created_at' =>$created_Dt
));
}
$insert_id = $this->db->insert_id();
}
}
Using the below, I echo a JSON array of the results. But this requires that I identify the column names which I'd like to return from the SQL query:
$new_sql = "SELECT TOP 200 * FROM STracker ORDER BY [ID] DESC";
$check_statement = sqlsrv_query($conn, $new_sql);
$data = array();
while($row = sqlsrv_fetch_array($check_statement, SQLSRV_FETCH_ASSOC)) {
$data['data'][] = array(
'id' => $row['ID'],
's_reference' => $row['s_reference'],
'reference' => $row['reference'],
'customer_name' => $row['customer_name']
);
}
Is there any way to create that array information, but return all of the columns returned by the query dynamically? So by using SELECT * FROM, all of the column data is returned in the array but without me needing to write out all of these individually? (the below)
'id' => $row['ID'],
's_reference' => $row['s_reference'],
'reference' => $row['reference'],
'customer_name' => $row['customer_name']
Ok I forgot to add that I'd tried this:
$data['data'][] = array($row);
Which is clearly wrong, and after using the following, it works perfectly!
$data['data'][] = $row;
The real question is how do I populate a Google charts datatable form a MySql query when a date is used for the first column?
I am trying to create a column chart using the Google Charts API. The problem is that the data is time series data. There are many dates represented. The way that this is done to create the data table is to assign column 0 to the date and each subsequent column represents the data being measured. That information is derived from the documentation. I just can't figure out how to get the data to assign to the subsequent columns. I have researched this extensively now and there are some answers that are close, but I can't make them work for this. Here is the code that is currently generating my chart data table:
$invArr = array('cols' => array(
array('label' => 'date', 'type' => 'date'),
array('label' => 'SKU', 'type' => 'number')),
'rows' => array());
while($row = mysql_fetch_row($query)) {
$invArr['rows'][] = array('c' => array(array('v' => $row[0]), array('v' => $row[1])));
}
I understand from the Google charts documentation that column 0 is always the date for continuous data. Each subsequent column is the data that is being measured, in this case ths SKU numbers. I need to have the first array in each row represent the date and the subsequent arrays represent the qtyoh data. I don't know how to do that.
I researched this for several days and I was finally able to solve the problem by piecing together answers to many different questions.
I started by querying the distinct dates and placing them into an array. The way this is done is very important because the date is a string when json encoded. It is important to parse it out and pass it in the Date(year,month,day) format exactly. It is also important that later on you use a variable to represent the date.
$dateArray = array();
while($row = mysql_fetch_row($queryDates)) {
$dtArray = explode('-',$row[0]);
$day = (int) $dtArray[1];
$month = ((int) $dtArray[0])-1;
$year = (int) $dtArray[2];
$dateArray[] = "Date($year, $month, $day)";
}
I then set up the columns for the table by looping through a query of the SKU's.
$invArr = array(
'cols' => array(
array('label' => 'Date', 'type' => 'date')
)
);
while($row = mysql_fetch_row($querySkus)) {
$invArr['cols'][] = array('label' => $row[0], 'type' => 'number');
}
I then query the quantities and place them into an array. I then loop through each value and populate the table array ($inVarr).
$quantities = array();
while($row = mysql_fetch_row($queryQty)) {
$quantities[] = (int) $row[0];
}
$qtyCounter = 0;
for($i=0;$i<count($dateArray);$i++) {
$invArr['rows'][] = array(
'c' => array(
array('v' => $dateArray[$i]),
array('v' => $quantities[$qtyCounter]),
array('v' => $quantities[$qtyCounter+1]),
array('v' => $quantities[$qtyCounter+2])
)
);
$qtyCounter=$qtyCounter+3;
}
I can then just echo the json encoded array which will return the data for the data table.
echo json_encode($invArr);
I believe that this is a bit clunky, but it works.
i'm newbie in Cake and wodering how to insert multiple rows in a single saveall function,
i got this table,
CREATE TABLE IF NOT EXISTS `dates` (
`date` varchar(10) COLLATE utf8_unicode_ci NOT NULL
)
what i'm trying to do is let user select start date and end date using JQuery calander, once submit all the dates between this range will be saved into database, i already got the array of dates eg:
`array(
(int) 0 => '5/8/2013',
(int) 1 => '6/8/2013',
(int) 2 => '7/8/2013',
(int) 3 => '8/8/2013',
)
`
then my controller looks like this:
public function index(){
if ($this->request->is('post')) {
$this->Date->create();
$data = array();
$data['dates']=array();
$startDate = $this->request->data['Date']['from'];
$endDate = $this->request->data['Date']['to'];
$datesBlocked = $this->loopDates($this->request->data['Date']['from'],$this->request->data['Date']['to']);
$data['dates'][] = $this->request->data['Blockdate']['from'];
$data['dates'][] = $this->request->data['Blockdate']['to'];
/*foreach($datesBlocked as $data) {
$data['dates'][] = $data;
}*/
if($this->Date->saveAll($data)) {
$this->Session->setFlash(__('done'));
if ($this->Session->read('UserAuth.User.user_group_id') == 1) {
// $this->redirect("/manages");
}
}
}
public function loopDates($from,$to){
$blockdates = array();
$start = strtotime($from);
$end = strtotime($to);
debug($start);
$counter = 0;
for($t=$start;$t<=$end;$t+=86400) {
$d = getdate($t);
$blockdates[$counter++] = $d['mday'].'/'.$d['mon'].'/'.$d['year'];
}
debug($blockdates);
return $blockdates;
}
issue was i can't get foreach work, if i uncomment the foreach, i got error said Illegal string offset 'dates' , so i commented that and try to only add the start date and end date to the array to see if that works, then i got another error said.
`array(
'dates' => array(
(int) 0 => '08/05/2013',
(int) 1 => '09/05/2013'
)
)
`
Notice (8): Array to string conversion [CORE\Cake\Model\Datasource\DboSource.php, line 1005]Code
cuz i'm trying to insert 2 values into one field...i know it should be sth like
`array(
'dates' => array( (int) 0 => '08/05/2013',
)
'dates' => array((int) 1 => '09/05/2013'
))
`but can't figure out how to do it. Any help would be much appreciate!!!!
The structure you'll want your array to save multiple dates using saveAll() is this:
array(
'Date' => array(
0 => array(
'date' => '08/05/2013',
),
1 => array(
'date' => '09/05/2013',
)
),
)
I know that this is a little late, but to write multiple rows in a loop, you have to proceed the save with a create().
eg:
foreach($items as $lineItem){
$this->Invoice->create();
$this->Invoice->save(array(
'user_id'=>$property['User']['id'],
'invoice_id'=>$invId['Invoices']['id'],
'item_id'=>$lineItem['item_number'],
'quantity'=>$lineItem['quantity'],
'price'=>$lineItem['mc_gross']
);
}
Just thought it was worth mentioning, hopefully it will help someone.