Notice (8): Undefined index: From when fetching message response from Google API-PHP Client - gmail-api

I am trying to list user messages in GMail Inbox.
$client = $this->getClient();
$service = new \Google_Service_Gmail($client);
$opt_param = array('labelIds' => 'INBOX');
$messagesResponse = $service->users_messages->listUsersMessages($user, $opt_param);
for ($i = 0; $i < $total; $i++) {
$messageToGet = ($messagesResponse->messages[$i]->id);
$message = $service->users_messages->get($user, $messageId);
$names = array_column($message->payload->headers, 'name');
$values = array_column($message->payload->headers, 'value');
$mail = array_combine($names, $values);
$senderMail = explode("<", $mail['From']);
if (count($senderMail) == 1) {
if (strpos($senderMail[0], '#') !== false) {
$senderName = [];
$domain[0] = substr($senderMail[0], strpos($senderMail[0], "#") + 1);
} else {
Log::info('Sender email could not be found');
return;
}
} else {
$senderName = [];
if ($senderMail[0] != "") {
$senderName = $senderMail[0];
$senderName = explode(" ", $senderName);
}
$senderMail = explode(">", $senderMail[1]);
$domain = explode("#", $mail['From']);
$domain = explode(">", $domain[1]);
}
...
}
When I tried to fetch 'From' from this $message response, it is throwing an undefined index error while fetching response for a message.
Notice: Notice (8): Undefined index: From in [File]
When I tried to debug the messages response return by the google api-php client, it resulted as below for all the messages
[16] => Google\Service\Gmail\MessagePartHeader Object
(
[name] => From
[value] => "Firstname Lastname" <firstname.lastname#gmail.com>
[internal_gapi_mappings:protected] => Array
(
)
[modelData:protected] => Array
(
)
[processed:protected] => Array
(
)
)
For one message, it returned
[16] => Google\Service\Gmail\MessagePartHeader Object
(
[name] => FROM
[value] => noreply#<domain>.org
[internal_gapi_mappings:protected] => Array
(
)
[modelData:protected] => Array
(
)
[processed:protected] => Array
(
)
)
Can anyone kindly let me know why the value of [name] key differs from From to FROM? Are there any more formats for the [name] key?
Thanks in Advance.

Related

How to loop properly through an array?

I'm trying to implement a solution to find out the MONTH that has the most number of pages. Does anyone know how to loop though this JSON array so that I can maybe extract the $total for each month ($total1, $total2, $total3, ...$total12) and then maybe add them to an array and then find the max number(meaning the Month that has most pages)?
This is the way I'm trying so far for a single month:
foreach($my_array as $value){
foreach ($value->all_books as $all_book) {
foreach ($all_book->number_of_pages as $num_page) {
if ($num_page->number_of_books && $num_page->pages) {
$total += $num_page->number_of_books * $num_page->pages;
}
}
}
}
You can count page count of month like this :
$monthWisePageCount = array();
foreach($my_array as $value){
$month = date('M', strtotime($value->datetime_status));
if(!in_array($month, array_keys($monthWisePageCount))){
$monthWisePageCount[$month]['count'] = 0;
$monthWisePageCount[$month]['month'] = date('F', strtotime($value->datetime_status));
}
foreach ($value->all_books as $all_book) {
foreach ($all_book->number_of_pages as $num_page) {
if ($num_page->number_of_books && $num_page->pages) {
$monthWisePageCount[$month]['count'] += $num_page->number_of_books * $num_page->pages;
}
}
}
}
print_r($monthWisePageCount);
The result will look like this
Array
(
[Mar] => Array
(
[count] => 900
[month] => March
)
[Dec] => Array
(
[count] => 558
[month] => December
)
[Oct] => Array
(
[count] => 280
[month] => October
)
)
You can find the largest item like this :
$largestKey = '';
$largestCount = 0 ;
foreach($monthWisePageCount as $key => $item){
if($item['count'] > $largestCount ) {
$largestCount = $item['count'];
$largestKey = $key;
}
}
$monthWithLargestPageCount = $monthWisePageCount[$largestKey];
print_r($monthWithLargestPageCount);
The result will be like this
Array ( [count] => 900 [month] => March )

Combined two arrays and the result returned has an empty key and value

I have an excel sheet which is read and converted to an array.
Here is the code :
$filename = $_FILES['importProjects']['tmp_name'];
$objPHPExcel = PHPExcel_IOFactory::load($filename);
$i = 0;
$all_sheet = $objPHPExcel->getSheetCount(); //total number of sheets
$arrayInsertProject = array();
$arrayUpdateProject = array();
while ($i < $all_sheet){
$objPHPExcel->setActiveSheetIndex($i);
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
$arrayCount = count($allDataInSheet); // Here get total count of rows from the sheet
$column = 'A';
$project_cnt=1;
$dataIns = array();
for ($row = 1; $row <= $arrayCount; $row++) { //loop through rows
if($row ==1){
$highestColumn = $objPHPExcel->getActiveSheet()->getHighestColumn();
$rowDataHeader = $objPHPExcel->getActiveSheet()->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
$rowDataHeader = array_reduce($rowDataHeader, 'array_merge', array());
}else {
$highestColumn = $objPHPExcel->getActiveSheet()->getHighestColumn();
$rowData = $objPHPExcel->getActiveSheet()->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
$dataIns = array_combine($rowDataHeader, $rowData);
}
}
}
When I print this array $dataIns, I get something like this :
Array
(
[intProjectSlNo] => 1069
[chvProjectNameEng] => New
[slug] => this-is -test
[nchvSecType] => 1754349
[] =>
)
How to remove the empty key => value pair ?
Add this after while loop of your code
foreach($dataIns as $key=>$value)
{
if(is_null($value) || $value == '')
unset($dataIns[$key]);
}
print_r($dataIns);

Rendering view for DOMPDF in phalconPHP

I have been try to convert template to PDF with DOMPDF in phalconPHP with angularJS at the front. But I am getting 500 internal server error response from it. DOMPDF is included fine in the controller as I loaded static HTML in load_html() function, it worked fine. Below is the report action from ReportsController. Don't bother with the whole code and just skip to the DOMPDF related code at the end. And $patients is the array that contains all the data which the template is going to need.
ReportController's reportAction:
public function reportAction()
{
$patientsModel = new Patients();
$patients = array();
$patients['data'] = array();
$tmpfilters = $this->queryfilters;
unset($tmpfilters['limit']);
$tmpfilters2 = array();
$tmpfilters2['models'] = "PRM\\Models\\Patients";
if( isset( $tmpfilters['conditions'] ) )
{
$tmpCondition = preg_replace("/[^0-9]/", '', $tmpfilters['conditions']);
$tmpfilters2['conditions'] = "clinic = " . $tmpCondition . " AND status = 24";
}
else
{
$tmpfilters2['conditions'] = "status = 24";
}
$tmpActivePatients = new Patients();
$tmpActivePatients = $tmpActivePatients->find($tmpfilters2);
$patients['activeTotal'] = $tmpActivePatients->count();
$tmpfilters3 = array();
$tmpfilters3['models']['m'] = "PRM\\Models\\Activity";
$tmpfilters3['models']['s'] = "PRM\\Models\\Patients";
if( isset( $tmpfilters['conditions'] ) )
{
$tmpCondition2 = preg_replace("/[^0-9]/", '', $tmpfilters['conditions']);
$tmpfilters3['conditions'] = "m.clinic = " . $tmpCondition2 . " AND " . "s.clinic = " . $tmpCondition2 . " AND m.patient=s.id AND m.duration > 1";
}
else
{
$tmpfilters3['conditions'] = "m.patient = s.id AND m.duration > 1";
}
$tmpPatientDuration = new Query($tmpfilters3);
$tmpPatientDuration = $tmpPatientDuration->getQuery()->execute();
//$builder = $this->modelsManager->createBuilder();
$patients['billableTotal'] = $tmpPatientDuration->count();
//$builder->addFrom('PRM\\Models\\Activity', 'a')->innerJoin('PRM\\Models\\Patients', 'p.id=a.patient', 'p')->where('a.duration > 1 AND p.status = 24');
//$result = $builder->getQuery()->execute();
//$patients['billableTotal'] = $result->count();
foreach ($tmpPatientDuration as $patient) {
array_push($patients['data'], array(
'id' => $patient->id,
'firstname' => $patient->s->firstname,
'lastname' => $patient->s->lastname,
'duration' => $patient->m->duration,
'billingCode' => "CPT 99490"));
/*'icd1' => Ccm::findFirstById($patient->icd1)->icdcode,
//'icd2' => Ccm::findFirstById($patient->icd2)->icdcode,
//'clinic' => Clinics::findFirstById($patient->clinic)->name,
'duration' => Activity::sum([
"column" => "duration",
"conditions" => "patient = '{$patient->id}'",
]),
'response' => Activity::findFirst([
"conditions" => "patient = '{$patient->id}' and activity='Communication' ",
"order" => "id desc"
])->description,
'status' => Status::findFirstById($patient->status)->name));*/
}
$html = $this->view->getRender("reports", "report", $patients);
$dompdf = new domPdf();
$dompdf->load_html($html);
$dompdf->setPaper('A4', 'landscape');
$dompdf->render();
//$this->response->setJsonContent($patients);
$this->response->setContentType('application/pdf');
$this->response->setContent($dompdf->stream());
$this->response->send();
}
Here is the angularJS controller's code:
$http.get('common/reports/report', {responseType: 'arraybuffer'}).success(
function (data) {
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
}).error(
function (data) {
angular.forEach(data, function (error) {
$scope.error[error.field] = error.message;
console.log(error.field);
});
$alert({title: 'Error!', content: data.flash.message, placement: 'top-right', type: data.flash.class , duration: 10, container: '.site-alert'});
}
);
error logs:
error log for the above problem

Array output value is null on separating string value using implode function by comma output displays in exta comma? how to solve it?

$drstring1 = stristr($drstring, 'DR', false);
//drupal_set_message($drstring1);
$drbrkstring = $drstring1;
$drval = explode('DR', $drbrkstring);
array_shift($drval);
$drdata_array = array();
foreach ($drval as $drv) {
$drdata = process_drstring('DR' . $drv);
$Colarray = array();
foreach ($drdata as $key => $value) {
array_push($Colarray, $key);
print 'key='. $key .' <br />';
}
$ColNames = implode(',' ,$Colarray);
print 'colunames=' .$ColNames.' <br />';
function process_drstring($string) {
$result = array();
$tag_text = array(
'DR' => 'segmenttag',
'01' => 'dateofentry',
'02' => 'dispute_remarks1',
'03' => 'dispute_remarks2',
'04' => 'dispute_remarks3',
'05' => 'dispute_remarks4',
'06' => 'dispute_remarks5',
'07' => 'dispute_remarks6',
);
$tag = substr($string, 0, 2);
$length = substr($string, 2, 2);
$data = substr($string, 4, $length);
$result[$tag_text[$tag]] = $data;
$newstring = substr($string, $length + 4, strlen($string));
if ($newstring) {
$newresult = process_drstring($newstring);
$result = array_merge($result, $newresult);
return $result;
}
else {
return $result;
}
}
output:
key=segmenttag
key=
key=dateofentry
key=dispute_remarks2
key=dispute_remarks1
key=dispute_remarks3
key=dispute_remarks4
key=dispute_remarks5
key=dispute_remarks6
colunames=segmenttag,,dateofentry,dispute_remarks2,dispute_remarks1,dispute_remarks3,dispute_remarks4,dispute_remarks5,dispute_remarks6
From this function , I need to get an columnames, but i'm receiving an extra key='' key element.
getting extra key value. Key='' it should not appear. Please help me solve this problem.

Passing an array as parameter on update_batch codeigniter

I want to pass array as a parameter to model. I little confuse, how to pass them.
CONTROLLER
public function update_json_detail() {
$post_data = $this->input->post("POST_ARRAY");
$execute = array();
foreach ($post_data as $data) {
$execute[] = array(
'ID'=> $data['0'],
'MATERIAL' => $data['7'],
'AC' => $data['8']
);
}
print_r($execute);
/* CODE TO INSERT BATCH */
$callback = $this->m_admin->update_eir_to_cost($execute);
}
To debug it, this is the result of those array
[{"ID":"68","MATERIAL":"Test","AC":"a"}, {"ID":"69","MATERIAL":"b","AC":"c"}]
This is the MODEL
public function update_eir_to_cost($id, $material, $ac) {
$data = array(
"MATERIAL" => $material,
"AC" => $ac
);
$this->db->trans_start();
$this->db->where($id);
$this->db->update_batch('tb_repair_detail', $data);
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE) {
// generate an error... or use the log_message() function to log your error
echo "Error Updating";
}
}
My case is, I want to use update_batch to update my table.
Actually, update material and AC where ID = ID
Any help it so appreciated.
The result you shown up for print_r($execute) is not correct. That should be the rerult for json_encode($execute). Here is the result for print_r($execute)
Array
(
[0] => Array
(
[ID] => 68
[MATERIAL] => Test
[AC] => b
)
[1] => Array
(
[ID] => 69
[MATERIAL] => a
[AC] => c
)
)
Now, in your model
public function update_eir_to_cost($data) {
$this->db->update_batch('tb_repair_detail', $data, 'ID');
// Produces:
// UPDATE `tb_repair_detail` SET `MATERIAL` = CASE
// WHEN `ID` = '68' THEN 'Test'
// WHEN `ID` = '69' THEN 'b'
// ELSE `name` END,
// `AC` = CASE
// WHEN `ID` = '68' THEN 'a'
// WHEN `ID` = '69' THEN 'c'
// ELSE `AC` END
// WHERE `ID` IN ('68','69')
}
Have a look at Updating Data

Resources