PHP - array_push() expects parameter 1 to be array, null given in - php

I'm currently experiencing issues where array_push() is not working. I have ensured the arrays are directly accessible and declared correctly. Yet I'm still receiving these warnings and the values are not being pushed onto the array.
Here is my code:
include('../connstr.inc');
$email=$_REQUEST["email"];
$datafile=$_REQUEST["datafile"];
$email_safe=preg_replace("/[^a-zA-Z]/","_",$email);
$path="../uploaded_data";
$xml = simplexml_load_file("{$path}/{$email_safe}/{$datafile}.xml");
// Retreive data details for specified activity
$lapCount = $xml->Activities->Activity->Lap->count();
// Lap Variables
$totalTime = array(); $distance = array(); $maxSpeed = array();
$calories = array(); $intensity = array(); $trigMethod = array();
$avgSpeed = array();
// Convert filename to DateTime format
$datafile = convertID($datafile);
$datafile = date('Y-m-d H:i:s', strtotime($datafile));
// Variables for accurate distance calculations
$polarDistance = true;
$lapID;
$totalLapDistance;
$firstPoint = array();
$secondPoint = array();
// Collect details for each lap
for($x = 0; $x < $lapCount; $x++) {
$totalLapDistance = 0;
$lapNumber = $x+1;
$totalTime[$x] = $xml->Activities->Activity->Lap[$x]->TotalTimeSeconds;
$distance[$x] = $xml->Activities->Activity->Lap[$x]->DistanceMeters;
$maxSpeed[$x] = $xml->Activities->Activity->Lap[$x]->MaximumSpeed;
$calories[$x] = $xml->Activities->Activity->Lap[$x]->Calories;
$intensity[$x] = $xml->Activities->Activity->Lap[$x]->Intensity;
$trigMethod[$x] = $xml->Activities->Activity->Lap[$x]->TriggerMethod;
$avgSpeed[$x] = $xml->Activities->Activity->Lap[$x]->Extensions->LX->AvgSpeed;
// Store activity details into the 'detail' table
$sqlLap = "INSERT INTO lap (lapDate,lapNumber,TotalTime,distance,maxSpeed,avgSpeed,calories,intensity,trigMethod) VALUES (\"$datafile\",\"$lapNumber\",\"$totalTime[$x]\",\"$distance[$x]\",\"$maxSpeed[$x]\",\"$avgSpeed[$x]\",\"$calories[$x]\",\"$intensity[$x]\",\"$trigMethod[$x]\")";
$runLap = mysql_query($sqlLap) or die("unable to complete INSERT action:$sql:".mysql_error());
// Trackpoint variables
$altitude = array(); $tDistance = array(); $latitude = array();
$longitude = array(); $speed = array(); $pointTime = array();
// Retreive lapID
$lapID = getLapID();
// Find how many tracks exist for specified lap
$trackCount = $xml->Activities->Activity->Lap[$x]->Track->count();
$trackpointTotalCount = 1;
for($t = 0; $t < $trackCount; $t++) {
// Find out how many trackpoints exist for each track
$trackpointCount = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint->count();
// Collect details for each specificied track point
for($tp = 0; $tp < $trackpointCount; $tp++) {
$altitude[$tp] = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint[$tp]->AltitudeMeters;
$tDistance[$tp] = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint[$tp]->DistanceMeters;
$pointTime[$tp] = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint[$tp]->Time;
$latitude[$tp] = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint[$tp]->Position->LatitudeDegrees;
$longitude[$tp] = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint[$tp]->Position->LongitudeDegrees;
$speed[$tp] = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint[$tp]->Extensions->TPX->Speed;
// Check Track point
if(checkTP($altitude[$tp], $tDistance[$tp], $latitude[$tp], $longitude[$tp], $speed[$tp])) {
// Check if accurate distance should be calculated
if($polarDistance) {
$aa = $latitude[$tp];
$bb = $longitude[$tp];
$cc = $altitude[$tp];
if($tp == 0) {
array_push($firstPoint, $aa, $bb, $cc);
} else if($tp != 0) {
array_push($secondPoint, $aa, $bb, $cc);
}
printArray($firstPoint);
printArray($secondPoint);
// Add distance between trackpoints to total lap distance
$totalLapDistance += calcDistance($firstPoint, $secondPoint);
}
// Insert current trackpoint data into 'trackpoint' table
$sqlTC = "INSERT INTO trackpoint (tpDate,tpNumber,altitude,distance,latitude,longitude,speed,pointTime) VALUES (\"$datafile\",\"$trackpointTotalCount\",\"$altitude[$tp]\",\"$tDistance[$tp]\",\"$latitude[$tp]\",\"$longitude[$tp]\",\"$speed[$tp]\",\"$pointTime[$tp]\")";
$runTC = mysql_query($sqlTC) or die("unable to complete INSERT action:$sql:".mysql_error());
}
$trackpointTotalCount++;
if($polarDistance) {
if($tp != 0) {
unset($firstPoint);
$firstPoint = &$secondPoint;
unset($secondPoint);
}
}
}
}
if($polarDistance) {
if($tp != 0) {
// Update lap with more accurate distance
echo $totalLapDistance . '<br />';
$sqlUlap = "UPDATE lap SET accDistance='$totalLapDistance' WHERE lapID = '$lapID' ";
$runUlap = mysql_query($sqlUlap) or die("unable to complete UPDATE action:$sql:".mysql_error());
}
}
}
I didn't include all of the code below as there is quite a lot and I very much doubt it's relevant.
The warnings themselves only appear when trying to push a variable onto $secondPoint:
array_push($secondPoint, $aa, $bb, $cc);
However values are not being pushed onto either of the variables ($firstPoint, $secondPoint)
As a test I did echo $aa,bb and $cc and they did contain correct values.
Anybody have an idea of what I'm doing wrong?
EDIT: I have showed more of the code as I do use these arrays later, however this should not affect how the values are initially pushed? Below is some code which may affect it, namely the assign by reference?
if($polarDistance) {
if($tp != 0) {
unset($firstPoint);
$firstPoint = &$secondPoint;
unset($secondPoint);
}
}

That unset($secondPoint) will probably do it.
Try this instead:
if($polarDistance) {
if($tp != 0) {
$firstPoint = $secondPoint;
$secondPoint = array();
}
}

Related

Php save more Array into MySQL

I'm trying to save arrays on a MySQL database with PHP.
The code inserts only the first line, if I have an array of 5 elements it just inserts the first element and the others and 4 don't save them for me.
Can anyone tell me where I'm wrong?
Thanks a lot.
<?php
//getting user values
$day = $_POST['Day'];
$nDay = $_POST['n_Day'];
$fieldOne = $_POST['Field_one'];
$fieldTwo = $_POST['Field_two'];
$timeOne = $_POST['Time_one'];
$timeTwo = $_POST['Time_two'];
$idR = $_POST['id_ristorante'];
$day_array = explode(",",$day);
$nDay_array = explode(",",$nDay);
$timeOne_array = explode(",",$timeOne);
$timeTwo_array = explode(",",$timeTwo);
$len = count($day_array and $nDay_array and $timeOne_array and $timeTwo_array);
$output=array();
//require database
require_once('db.php');
//checking if email exists
$conn=$dbh->prepare('SELECT id_ristorante FROM Orari WHERE id_ristorante=:idR');
$conn->bindParam(':idR', $idR, PDO::PARAM_STR);
$conn->execute();
//results
if($conn->rowCount() !==0){
$output['isSuccess'] = 0;
$output['message'] = "Orario già inserito";
} else {
for($i=0;$i<$len;$i++){
$day = $day_array[$i];
$nDay = $nDay_array[$i];
$timeOne = $timeOne_array[$i];
$timeTwo = $timeTwo_array[$i];
$conn=$dbh->prepare('INSERT INTO Orari (Day, n_Day, Field_one, Field_two, Time_one, Time_two, id_ristorante) VALUES (?,?,?,?,?,?,?)');
//encrypting the password
$conn->bindParam(1,$day);
$conn->bindParam(2,$nDay);
$conn->bindParam(3,$fieldOne);
$conn->bindParam(4,$fieldTwo);
$conn->bindParam(5,$timeOne);
$conn->bindParam(6,$timeTwo);
$conn->bindParam(7,$idR);
$conn->execute();
if($conn->rowCount() == 0) {
$output['isSuccess'] = 0;
$output['message'] = "Errore, riprova.";
} elseif($conn->rowCount() !==0){
$output['isSuccess'] = 1;
$output['message'] = "Orari salvati!";
}
}
}
echo json_encode($output);
?>
When you trying to do count on multiple array as:
$len = count($day_array and $nDay_array and $timeOne_array and $timeTwo_array);
The and cause the array to be boolean evaluated so the final assign to $len is 1 and that why the loop is done only once and only the first element is inserted to DB.
If all the array in the same length you should just do count on 1 of them as:
$len = count($day_array)
Better practice will be to do count on each on them and then assign $len with the minimum value
Change this line
$len = count($day_array and $nDay_array and $timeOne_array and $timeTwo_array);
To
$len = count($day_array) + count($nDay_array) + count($timeOne_array) + count($timeTwo_array);

Why my Cakephp web service query takes lot of time to return data?

I've got a web service which takes around 15 secs to return JSON response to front-end.My code looks like this:
Controller code:
public function getDetailReport($data){
$user_id = $data->user_id;
$test_id = $data->test_id;
$result_obj = new TestSetDetailResultTable();
$data_array = $result_obj->getDetailReportByUser($user_id, $test_id);
if($data_array['status'] == 1) {
echo $this->successMessage('successfully Executed',$data_array['record']);
} else {
echo $this->failMessage($data_array['error'],$data_array['message']);
}
exit;
}
Model code:
public function getDetailReportByUser($user_id,$test_id) {
$data_array = Array();
$subject_array = Array();
$answer_array = Array();
$topper_array = Array();
$percentile_array = Array();
$max_marks = 0;
$perc = 0;
$hrs = 0;
$mint = 0;
$sec = 0;
$query = new AppQuery();
$query->callProcedure('getSummaryResult',array($test_id,$user_id));
$row_list = $this->loadRowList($query);
if(count($row_list) > 0) {
$max_marks = $row_list[0]->maximum_marks;
$perc = $row_list[0]->percentage;
$query->callProcedure('getCompletedTestTime',array($user_id,$test_id));
$row_time = $this->loadRowList($query);
$query->callProcedure('getAllUserPerTest',array($test_id));
$row_user = $this->loadRowList($query);
if(count($row_time)> 0 && count($row_user) > 0) {
foreach ($row_list as $list) {
$item['test_name'] = $list->test_name;
$item['total_question'] = $list->total_question;
$item['right_answer'] = $list->right_answer;
$item['wrong_answer'] = $list->wrong_answer;
$item['question_attempted'] = $list->question_attempted;
$item['question_not_attempted'] = $list->question_not_attempted;
$item['positive_marks'] = $list->positive_marks;
$item['negative_marks'] = $list->negative_marks;
$item['obtaine'] = $list->obtaine;
$item['maximum_test_time'] = $list->maximum_test_time;
$item['maximum_marks'] = $list->maximum_marks;
$item['test_date'] = $list->test_date;
$number = floatval($list->obtaine)* 100 / intval($list->maximum_marks);
$item['percentage'] = number_format($number, 2, '.', ''); // upto 2 decimal places
$data_array['detail'] = $item;
}
$tmp = Array();
$hrs = $row_time[0]->spent_hours;
$mint = $row_time[0]->spent_minute;
$sec = $row_time[0]->spent_second;
$completed_minute = $row_time[0]->compeleted_minute;
$completed_second = $row_time[0]->compeleted_second;
if($completed_second < 0) {
$completed_second = -1 * $completed_second; // only removing - sign
}
$tmp = $this->calculateTime($hrs, $mint, $sec);
$tmp['compeleted_minute'] = $completed_minute;
$tmp['compeleted_second'] = $completed_second;
$data_array['time'] = $tmp;
foreach ($row_user as $list) {
$tem['total_user'] = $list->total_user;
$data_array['users'] = $tem;
}
// Now get The subject wise Result
$temp = Array();
$query->callProcedure('getTestResult',array($test_id,$user_id));
$subject_result = $this->loadRowList($query);
foreach ($subject_result as $res) {
$temp['subject_name']= $res->subject_name;
$temp['marks_obtained'] = $res->obtaine;
$temp['total_question'] = $res->total_question;
$temp['question_attempted'] = $res->question_attempted;
$temp['wrong_answer'] = $res->wrong_answer;
// $temp['total_spent_hours'] = $res->total_spent_hours;
// $temp['total_spent_minute'] = $res->total_spent_minute;
// $temp['total_spent_second'] = $res->total_spent_second;
$time_arr2 = $this->calculateTime($res->total_spent_hours, $res->total_spent_minute, $res->total_spent_second);
$temp['total_spent_hours'] = $time_arr2['hours'];
$temp['total_spent_minute'] = $time_arr2['minute'];;
$temp['total_spent_second'] = $time_arr2['second'];
$temp['max_marks'] = intval($res->total_question) * intval($res->positive_marks);
$subject_array[] = $temp;
}
$data_array['subject_result'] = $subject_array;
//>>>>>>>>>>> Now get Answer of Question with Time spent>>>>>>>>>>
$temp = Array();
$query->callProcedure('getAnswerwithTime',array($test_id,$user_id));
$answer_list = $this->loadRowList($query);
foreach ($answer_list as $res) {
$temp['question']= utf8_encode($res->question);
$temp['user_answer']= $res->user_answer;
$temp['correct_answer'] = $res->correct_answer;
$temp['spent_hours'] = $res->spent_hours;
$temp['spent_minute'] = $res->spent_minute;
$temp['spent_second'] = $res->spent_second;
$temp['obtaine'] = $res->obtaine;
$answer_array[] = $temp;
}
$data_array['answer_with_time'] = $answer_array;
/*>>>>>>>>End>>>>>>>>>>>>>*/
/*>>>>>>>>>>>>>>For Topper result for Comparing>>>>>>>>>>>>>>>>*/
$temp = Array();
$query->callProcedure('getTopperResult',array($test_id));
$top_arr = $this->loadRowList($query);
foreach ($top_arr as $top) {
$temp['user_name'] = $top->user_name;
$temp['test_name'] = $top->test_name;
$temp['total_question'] = $top->total_question;
$temp['right_answer'] = $top->right_answer;
$temp['wrong_answer'] = $top->wrong_answer;
$temp['question_attempted'] = $top->question_attempted;
$temp['question_not_attempted'] = $top->question_not_attempted;
$temp['positive_marks'] = $top->positive_marks;
$temp['negative_marks'] = $top->negative_marks;
$temp['maximum_marks'] = $top->maximum_marks;
$temp['obtaine'] = $top->obtaine;
$temp['percentage'] = $top->percentage;
$temp['maximum_test_time'] = $top->maximum_test_time;
$temp['test_date'] = $top->test_date;
$timer = $this->calculateTime( $top->spent_hours, $top->spent_minute, $top->spent_second);
$temp['spent_hours'] = $timer['hours'];
$temp['spent_minute'] = $timer['minute'];
$temp['spent_second'] = $timer['second'];
$temp['completed_minute'] = $top->completed_minute;
$sec_var = $top->completed_second;
if($sec_var < 0) {
$sec_var = -1 * $sec_var;
}
$temp['completed_second'] = $sec_var;
$percentile = $this->getPercentileRank($test_id,$top->percentage,$top->maximum_marks);
$temp['percentile'] = $percentile; // percentile
// $temp['rank'] = intval($percentile); // Rank
$topper_array[] = $temp;
}
//>>>>>>>>>>>>>>>>>> topper array contain Topper Percentile,now we need to get Rank according to Percentile
$topper_array = $this->rank($topper_array);
$data_array['toppers_result'] = $topper_array;
/*>>>>>>>>>>>>>>For Topper Result>>>>>>>>>>>>>>>>*/
/*>>>>>>>>>>>>>>For Login user Percentile>>>>>>>>>>>>>>>>*/
$percentile = $this->getPercentileRank($test_id, $perc, $max_marks);
$percentile_array = $this->loginUserRank($topper_array, $percentile);
$data_array['percentile'] = $percentile_array;
/*>>>>>>>>>>>>>>For Login user Percentile End>>>>>>>>>>>>>>>>*/
/*>>>>>>>>>Get subject Wise Time of Toppers >>>>>>>>>>>>>*/
$subject_wise_time = $this->getSubjectWiseTopperTime($test_id);
$data_array['subject_wise_topper_time'] = $subject_wise_time;
/*>>>>>>>>>Get subject Wise Time of Toppers End >>>>>>>>>>>>>*/
/*>>>>>>>>>Get Answer with Time of Toppers >>>>>>>>>>>>>*/
$topper_answer_with_time = $this->topperAnswerTime($test_id);
$data_array['topper_answer_with_time'] = $topper_answer_with_time;
/*>>>>>>>>>Get Answer with Time of Toppers Ends >>>>>>>>>>>>>*/
return $this->modelMessage(1,'non','success',$data_array); exit;
} else {
return $this->modelMessage($this->getStatus(),$this->getError(),$this->getMessage()); exit;
}
} else {
return $this->modelMessage($this->getStatus(),$this->getError(),$this->getMessage()); exit;
}
}
I'm trying to debug this code but I don't know what am I missing here.How can this take 15 secs of time to return response back? Have I done something wrong?
When you debug than calculate the needed times with microtime(true), my guess are the DB querys for instance:
$start=microtime(true);
$answer_list = $this->loadRowList($query);
$stop=microtime(true);
$neededTime=$stop-$start;
echo "Time for answer_list $neededTime s for query $query";
Than you see what need to longest time. Than look on your query an look on your database schema. In most cases you can solve that issue by adding some indices on your db table. You can "debug" the query with explain on sql level, this will show you if you use an index.

PHP pagination. End array has different number of values than the initial query

Up until now I've always been limiting my pages for any pagination simply using MySQL LIMIT. It's been performing well.
However... Now I've written an application that grabs the data from 3 separate MySQL tables, after that I'm using array_multisort() to sort them.
The main issue here is that it is used for SMS messages(gammu smsd). If I write a message consisting of let's say 900 characters - it is split to 7 entries in the database. It is split every 139 characters (the number might be different sometimes)
Below code somewhat fixes this issue based on 'SequencePosition' field in the database.
So if I were to LIMIT it using MySQL I would have less results than I specified since MySQL has no idea what I'm doing with the data later.
I hope it makes sense to you guys.
How would you solve this issue? Can you think of a better way to do it? I mean- grabbing all the data from the table is rarely a good idea ;(
See PHP code below.
<?php
if(isset($_SESSION['id']))
{
if(isset($_GET['contact_number']) && ($_GET['contact_name']))
{
if (isset($_GET["page"]))
{
$page = $_GET["page"];
}
else
{
$page = 1 ;
}
$gmessages_page = 30; //this is actually a static value, normally it resides in a config file
$start_from = ($page-1) * $gmessages_page;
$contact_number = base64_decode($_GET['contact_number']);
$contact_name = base64_decode($_GET['contact_name']);
$query_inbox = "SELECT ReceivingDateTime, SenderNumber, TextDecoded FROM inbox WHERE SenderNumber='$contact_number' ORDER BY ReceivingDateTime";
$query_sentitems = "SELECT SendingDateTime, DestinationNumber, TextDecoded, Status, SequencePosition FROM sentitems WHERE DestinationNumber='$contact_number' ORDER BY SendingDateTime";
$query_outbox = "SELECT SendingDateTime, DestinationNumber, TextDecoded FROM outbox WHERE DestinationNumber='$contact_number' ORDER BY SendingDateTime";
$result_inbox = $conn->query($query_inbox);
$result_sentitems = $conn->query($query_sentitems);
$result_outbox = $conn->query($query_outbox);
if(!$result_inbox || !$result_sentitems || !$result_outbox)
{
die("Błąd połączenia z bazą (!RESULT)");
}
$rows_inbox = $result_inbox->num_rows;
$rows_sentitems = $result_sentitems->num_rows;
$rows_outbox = $result_outbox->num_rows;
if($rows_inbox == 0 || $rows_sentitems == 0)
{
$conn->close();
}
//inbox
$inbox_person = $contact_name;
for($j = 0; $j < $rows_inbox ; ++$j)
{
$result_inbox->data_seek($j);
$row_inbox = $result_inbox->fetch_array(MYSQLI_NUM);
$inbox_date[] = $row_inbox[0];
$inbox_number = $row_inbox[1];
$inbox_text[] = $row_inbox[2];
$sent_status[] = 0;
$sent_sequence_position[] = 0;
$inbox_type[] = 1;
}
for($j = 0; $j < $rows_sentitems ; ++$j)
{
$result_sentitems->data_seek($j);
$row_sentitems = $result_sentitems->fetch_array(MYSQLI_NUM);
if($row_sentitems[4] == 1)
{
$sent_sequence_position[] = $row_sentitems[4];
$inbox_date[] = $row_sentitems[0];
$inbox_text[] = $row_sentitems[2];
$sent_status[] = $row_sentitems[3];
$inbox_type[] = 2;
}
else
{
$inbox_text[sizeof($inbox_type) - 1] .= $row_sentitems[2];
}
}
for($j = 0; $j < $rows_outbox ; ++$j)
{
$result_outbox->data_seek($j);
$row_outbox = $result_outbox->fetch_array(MYSQLI_NUM);
$inbox_date[] = $row_outbox[0];
$inbox_text[] = $row_outbox[2];
$sent_status[] = "QueuedForSending";
$inbox_type[] = 2;
}
$number_of_records = sizeof($inbox_date);
$number_of_pages = ceil($number_of_records / $gmessages_page);
array_multisort($inbox_date, $inbox_text, $inbox_type, $sent_status, $sent_sequence_position);
$smarty->assign("inbox_date", $inbox_date);
$smarty->assign("inbox_text", $inbox_text);
$smarty->assign("inbox_number", $inbox_number);
$smarty->assign("inbox_person", $contact_name);
$smarty->assign("inbox_type", $inbox_type);
$smarty->assign("sent_status", $sent_status);
$smarty->assign("start_from", $start_from);
$smarty->assign("gmessages_page", $gmessages_page);
$smarty->assign("number_of_pages", $number_of_pages);
$smarty->assign("number_of_records", $number_of_records);
$smarty->assign("sent_sequence_position", $sent_sequence_position);
$smarty->assign("page", $page);
//for $_GET after sending SMS
$smarty->assign("contact_number_enc", $_GET['contact_number']);
$smarty->assign("contact_name_enc", $_GET['contact_name']);
$smarty->display('templates/conversation_body.tpl');
}
}
else
{
$smarty->display('templates/login_body.tpl');
}

PHP for each for items in array with Drupal

I am trying to calculate a value based on a price field in an entity reference field.
I currently have this, which works...
if (isset($entity->field_choose_a_package['und'][0]['target_id'])) {
$package1nid = $entity->field_choose_a_package['und'][0]['target_id'];
$package1 = node_load($package1nid);
$package1price = $package1->field_price['und'][0]['value'];
} else {
$package1price = 0;
}
if (isset($entity->field_choose_a_package['und'][1]['target_id'])) {
$package2nid = $entity->field_choose_a_package['und'][1]['target_id'];
$package2 = node_load($package2nid);
$package2price = $package2->field_price['und'][0]['value'];
} else {
$package2price = 0;
}
if (isset($entity->field_choose_a_package['und'][2]['target_id'])) {
$package3nid = $entity->field_choose_a_package['und'][2]['target_id'];
$package3 = node_load($package3nid);
$package3price = $package3->field_price['und'][0]['value'];
} else {
$package3price = 0;
}
$packagestotal = $package1price + $package2price + $package3price;
$entity_field[0]['value'] = $packagestotal;
However, there could be an unlimited amount of packages added, and rather than me replicate the code for 20+ packages to try and cover my bases, there must be a way I can do a for each loop.
I have tried something like this,
$arr = $entity->field_choose_a_package['und'];
foreach ($arr as &$value) {
if (isset($entity->field_choose_a_package['und'][$value]['target_id'])) {
$package1nid = $entity->field_choose_a_package['und'][$value]['target_id'];
$package1 = node_load($package1nid);
$package1price = $package1->field_price['und'][$value]['value'];
} else {
$package1price = 0;
}
}
unset($value);
but I cant figure out how to increment the variables, or if even need to? Can i just calculate the totals from the foreach?
$packagestotal = 0;
$numPackages = 3;
for($i = 0; $i <= $numPackages; $i++) {
if(isset($entity->field_choose_a_package['und'][$i]['target_id'])) {
${'package' . $i . 'nid'} = $entity->field_choose_a_package['und'][$i]['target_id'];
${'package' . $i} = node_load(${'package' . $i . 'nid'});
$packagestotal += ${'package' . $i}->field_price['und'][0]['value'];
}
}
$entity_field[0]['value'] = $packagestotal;
That should work.
Although, I would recommend that you wrap the package variables in an array rather than using variable variables as then the code would be much more readable and you could access each package attribute using $package[$i]

Getting remainding lines in a CSV

I have a script here which will get all the lines in a csv and insert them into a database (FileMaker to be exact), and I want it to count to 100 lines, break the loop, then tell me the remainding lines which are left. My code is below, Please see and any help would be greatly appreciated.
public function insertTimesheet() {
//Get the public variables
$fm = $this->fm;
$timesheet = $this->data['timesheets'];
$total = count($timesheet);
$fm = $this->fm;
$count = 0;
$total = count($timesheet);
//Loop through the data items in the array
foreach ($timesheet as $element) {
//Checks each key value in the array
for ($i = 0; $i < count($timesheet); ++$i) {
if($i == 100){
printf('%d Timesheets added', $i);
break;
// Return which timesheets have not been added //
}
//Prevents duplicate entries
$count++;
//Manually add some data to the array
$timesheet[$i]['Created_By_Staff_ID'] = $_SESSION["user"]->staff_id;
$timesheet[$i]['Key_Staff_ID'] = $_SESSION["user"]->staff_id;
$timesheet[$i]['Timesheet_Type'] = 'CSV_UPLOAD';
$timesheet[$i]['Resource_ID'] = 'N/A At this time [CSV UPLOAD]';
//Convert the dates to USA dates (FileMaker Format)
$timesheet[$i]['Date_From'] = $this->convertDate($timesheet[$i]['Date_From']);
$timesheet[$i]['Date_To'] = $this->convertDate($timesheet[$i]['Date_To']);
//Insert the data into the Database
$addReq = & $fm->createRecord('Web_Staff_Timesheet', $timesheet[$i]);
$result = $addReq->commit();
//Checks for filemaker errors
if (!FileMaker::isError($result)) {
$return['error'] = false;
$return['msg'] = 'Timesheet added successfully';
$strOut = sprintf('<br />Working on %d of %d timesheets', $count, $total);
//return true;
} else {
$return['error'] = true;
$return['errorCode'] = $result->code;
$return['msg'] = 'Unable to add Timesheet';
$strOut = sprintf('<br />Sorry, we could not add your time sheet, FileMaker Produced this error: %s <br /> Failed to insert the following timesheets [Line number]: ', $return['errorCode'], $count);
return false;
}
}
break;
}
//Clear the array to prevent duplicates
unset($timesheet, $element, $this->data);
return $strOut;
}
Just FYI guys, I've sorted it out now. Thanks for your time anyways!

Categories