I'm using Code Igniter,I try to add $finalamount to the result_array.
$this->db->select('customer_id, customer_ref, i_points, group_points, created_on');
$run_q = $this->db->get('employees');
if($run_q->num_rows() > 0){
foreach ($run_q->result_array() as $get) {
$totalpoints = $get['i_points'] + $get['group_points'];
$percent = 17;
$amountbycustomer = $totalpoints * 26 * $percent;
$amountbypref = $this->final($get['customer_id'],$percent);
$finalamount = $amountbycustomer + $amountbypref;
$get['finalamount'] = $finalamount;
}
return $run_q->result_array();
}
But in my view, this error
<td class="employeeCustomer"><?=$get['customer_id']?></td>
<td class="employeeCustomerRef"><?=$get['customer_ref']?></td>
<td class="employeeAmount"><?=$get['finalamount']?></td>//line 65
Message: Undefined index: finalamount
Filename: employees/employeeslist.php
Line Number: 65
You are returning just the result array from the db and not actually adding the final amount to the individual rows. You have to do something like this:
public function stmt() {
$this->db->select('customer_id, customer_ref, i_points, group_points, created_on');
$run_q = $this->db->get('employees');
if ($run_q->num_rows() > 0) {
$rows = $run_q->result_array();
foreach ($rows as $k => $get) {
$totalpoints = $get['i_points'] + $get['group_points'];
$percent = 17;
$amountbycustomer = $totalpoints * 26 * $percent;
$amountbypref = $this->final($get['customer_id'], $percent);
$finalamount = $amountbycustomer + $amountbypref;
$rows[$k]['finalamount'] = $finalamount;
}
return $rows;
}
return false;
}
OR using pass by reference (notice: &get):
$rows = $run_q->result_array();
foreach ($run_q->result_array() as &$get) {
$totalpoints = $get['i_points'] + $get['group_points'];
$percent = 17;
$amountbycustomer = $totalpoints * 26 * $percent;
$amountbypref = $this->final($get['customer_id'], $percent);
$finalamount = $amountbycustomer + $amountbypref;
$get['finalamount'] = $finalamount;
}
return $rows;
Related
I have a sum in my code that needs the return of a function, but the return of this function depends that the sum is already ready, because it uses a parameter that is still going to be created, can you solve it?
It's a calculator made in excel and I'm programming, but excel is that way and it works, but when I went to the code I got caught up in that problem.
//See the code:
public function valorRenda($rendaMensal, $valorEntrada, $tempoMeses, $imovelTipo){
$resultado = array();
$resultado['tipoSimulacao'] = 'rendaCliente';
$taxaMensal = $this->taxaPorTipo('rendaCliente', $imovelTipo, $rendaMensal) / 100;
//Cálculo do valor da primeira parcela
$primeiraParcela = $rendaMensal * 0.3;
//Calcula valor máximo do financiamento
$multiplicador = 0.5;
$i = 1;
for ($i = 1; $i <= 9999999999; $i++) {
$amortizacao = ($i * $multiplicador) / $tempoMeses;
$juros = (($i * $multiplicador) * ($taxaMensal));
$valor = $amortizacao + $juros + $this->custoMensal($valorImovel,$valorEntrada);
if ($valor >= $primeiraParcela) {
$projecao = ($i * $multiplicador) + $valorEntrada;
$valorImovel = ($projecao * $primeiraParcela / $valor);
break;
}
}
$financiamentoMaximo = round($valorImovel);
$financiamentoMaximo = $this->formatoReal($financiamentoMaximo);
$resultado['financiamentoMaximo'] = $financiamentoMaximo;
$resultado['financiamentoMaximoFormatado'] = $this->formatoReal($financiamentoMaximo, false);
//Calcula a primeira parcela
$primeiraParcelaSemTaxas = $primeiraParcela - $this->custoMensal($valorImovel,$valorEntrada);
$primeiraParcelaSemTaxas = round($primeiraParcelaSemTaxas, 2);
$primeiraParcelaSemTaxas = $this->formatoReal($primeiraParcelaSemTaxas);
$resultado['primeiraParcela'] = $primeiraParcelaSemTaxas;
$resultado['primeiraParcelaFormatado'] = $this->formatoReal($primeiraParcelaSemTaxas, false);
$primeiraParcelaTotal = $primeiraParcela;
$primeiraParcelaTotal = round($primeiraParcelaTotal, 2);
$primeiraParcelaTotal = $this->formatoReal($primeiraParcelaTotal);
$resultado['primeiraParcelaTotal'] = $primeiraParcelaTotal;
$resultado['primeiraParcelaTotalFormatado'] = $this->formatoReal($primeiraParcelaTotal, false);
$valorUltimaParcela = ((($valorImovel - $valorEntrada) - ((($valorImovel - $valorEntrada) / $tempoMeses) * ($tempoMeses - 1))) + ((($valorImovel - $valorEntrada) - ((($valorImovel - $valorEntrada) / $tempoMeses) * ($tempoMeses - 1)))) * $taxaMensal) + $this->custoMensal($valorImovel,$valorEntrada);
$ultimaParcelaSemTaxas = $valorUltimaParcela - $this->custoMensal($valorImovel,$valorEntrada);
$ultimaParcelaSemTaxas = round($ultimaParcelaSemTaxas, 2);
$ultimaParcelaSemTaxas = $this->formatoReal($ultimaParcelaSemTaxas);
$resultado['ultimaParcela'] = $ultimaParcelaSemTaxas;
$resultado['ultimaParcelaFormatado'] = $this->formatoReal($ultimaParcelaSemTaxas, false);
$primeiraParcelaTotal = $valorUltimaParcela;
$primeiraParcelaTotal = round($primeiraParcelaTotal, 2);
$primeiraParcelaTotal = $this->formatoReal($primeiraParcelaTotal);
$resultado['ultimaParcelaTotal'] = $primeiraParcelaTotal;
$resultado['ultimaParcelaTotalFormatado'] = $this->formatoReal($primeiraParcelaTotal, false);
$resultado['taxa'] = number_format(round(($taxaMensal * 100), 2), 2);
$resultado['periodo'] = $tempoMeses;
$this->incluiCustoMensal($resultado);
return $resultado;
}
//The function:
private function custoMensal($valorImovel, $entradaImovel)
{`enter code here`
$taxa_dfi = ($this->dfi / 100) * $valorImovel;
$taxa_mip = ($this->mip / 100) * ($valorImovel- $entradaImovel);
return $taxa_dfi + $taxa_mip + $this->tac;
}
Where is the problem:
$valor = $amortizacao + $juros + $this->custoMensal($valorImovel,$valorEntrada);
In this line I need to pass $valorImovelto the function custoMensal(), what happens is that the variable $valorImovel has not yet been created because it depends on the variable $valor.
I get the following error when I try to paginate in Laravel 5.2.
BadMethodCallException in Macroable.php line 81: Method paginate does
not exist.
And code:
Illuminate\Contracts\Pagination\Paginator;
...
$count = 0;
$gdprecords = Gdprecord::all();
foreach($gdprecords as $gdprecord) {
$count++;
$Pa = $gdprecord->adultpopulation;
$Pc = $gdprecord->childpopulation;
$P = $Pa + $Pc; // total population
$T = ($gdprecord->gdpcapita * $P) * $gdpratio; // basic income for country
if($bi_ratio == 0) {
$gdprecord->bi_adult = round($T / $Pa, 2);
} else {
$gdprecord->bi_adult = round($T / ($Pa + ($Pc / $bi_ratio)), 2);
}
$gdprecord->bi_adult_monthly = round($gdprecord->bi_adult / 12, 2);
$gdprecord->bi_adult_daily = round($gdprecord->bi_adult / 365, 2);
if($bi_ratio == 0) {
$gdprecord->bi_child = 0;
} else {
$gdprecord->bi_child = round($gdprecord->bi_adult / $bi_ratio, 2);
}
$gdprecord->bi_child_monthly = round($gdprecord->bi_child / 12, 2);
$gdprecord->bi_child_daily = round($gdprecord->bi_child / 365, 2);
}
$sorted_gdprecords = $gdprecords->sortByDesc('bi_adult')->paginate(25);
I don't want to paginate until after the array has been sorted. How do I make this work?
Thanks, Philip
Here is a solution I found, borrowing code from someone else:
public function paginate($items,$perPage)
{
$pageStart = \Request::get('page', 1);
// Start displaying items from this number;
$offSet = ($pageStart * $perPage) - $perPage;
// Get only the items you need using array_slice
$itemsForCurrentPage = array_slice($items, $offSet, $perPage, true);
return new LengthAwarePaginator($itemsForCurrentPage, count($items), $perPage,Paginator::resolveCurrentPage(), array('path' => Paginator::resolveCurrentPath()));
}
and add this code:
$gdprecords2 = $gdprecords->sortByDesc('bi_adult')->all();
$perPage = 25;
$sorted_gdprecords = self::paginate($gdprecords2, $perPage);
Thanks for your help. -Philip
Is there any way I could rewrite this function with an array instead of all these if statements? Could i maybe use some for loop together with an array? How would that look like? Any suggestions of simpler code?
Here is my php function:
function to_next_level($point) {
/*
**********************************************************************
*
* This function check how much points user has achievents and how much procent it is until next level
*
**********************************************************************
*/
$firstlevel = "3000";
$secondlevel = "7000";
$thirdlevel = "15000";
$forthlevel = "28000";
$fifthlevel = "45000";
$sixthlevel = "80000";
if($point <= $firstlevel) {
$total = ($point/$firstlevel) * 100;
$remaining = round($total);
//echo number_format($remaining, 0, '.', ' ');
return $remaining;
} elseif ($point <= $secondlevel) {
$total = ($point/$secondlevel) * 100;
$remaining = round($total);
//echo number_format($remaining, 0, '.', ' ');
return $remaining;
} elseif ($point <= $thirdlevel) {
$total = ($point/$thirdlevel) * 100;
$remaining = round($total);
//echo number_format($remaining, 0, '.', ' ');
return $remaining;
} elseif ($point <= $forthlevel) {
$total = ($point/$forthlevel) * 100;
$remaining = round($total);
//echo number_format($remaining, 0, '.', ' ');
return $remaining;
} elseif ($point <= $fifthlevel) {
$total = ($point/$fifthlevel) * 100;
$remaining = round($total);
//echo number_format($remaining, 0, '.', ' ');
return $remaining;
} elseif ($point <= $sixthlevel) {
$total = ($point/$sixthlevel) * 100;
$remaining = round($total);
//echo number_format($remaining, 0, '.', ' ');
return $remaining;
}
}
Try this:
function to_next_level($point) {
/*
**********************************************************************
*
* This function check how much points user has achievents and how much procent it is until next level
*
**********************************************************************
*/
$levelArray = array(3000, 7000, 15000, 28000, 45000, 80000);
foreach ($levelArray as $level)
{
if ($point <= $level) {
$total = ($point/$level) * 100;
$remaining = round($total);
//echo number_format($remaining, 0, '.', ' ');
return $remaining;
}
}
}
Start using OOP programming style. This is the perfect opportunity since it is a task without much complexity. Create a class that acts as central authority. That class can receive more methods over time. That way your code stays easy to maintain since all those functions are kept inside a class.
<?php
class levelAuthority
{
public static $thresholds = [ 3000, 7000, 15000, 28000, 45000, 80000 ];
public static function getDistanceToNextlevel($points)
{
foreach (self::$thresholds as $threshold) {
if ($points <= $threshold) {
$total = ($points/$threshold) * 100;
$remaining = round($total);
return $remaining;
}
}
}
}
// in the calling scope:
$points = 5000;
echo levelAuthority::getDistanceToNextlevel($points);
lots of answers to this!!
here is mine using a while loop - single exit point outside the loop:
function to_next_level($point) {
/*
**********************************************************************
*
* This function check how much points user has achievements and how much percent it is until next level
*
**********************************************************************
*/
$arr_level = array(3000,15000,28000,45000,80000);
$remaining = false;
while (!$remaining and list($key,$level) = each($arr_level)) {
if ($point <= $level) {
$total = ($point/$level) * 100;
$remaining = round($total);
}
}
// will return false if $point is greater than highest value in $arr_level
return $remaining;
}
You could write an additional function, that does the calculations and trigger it from the if/else if/else blocks.
function calculate_remaining($points, $level) {
$total = ($point/$level) * 100;
$remaining = round($total);
return $remaining;
}
You'd trigger this like:
if($point <= $firstlevel) {
return $calculate_remaining($point, $firstlevel);
} elseif ($point <= $secondlevel) {
return $calculate_remaining($point, $secondlevel);
} etc.
What about something like this?
function to_next_level($point)
{
$levels = array(
3000,
7000,
15000,
28000,
45000,
80000
);
foreach ($levels as $level)
{
if ($point <= $level)
{
$total = ($point / $level) * 100;
$remaining = round($total);
//echo number_format($remaining, 0, '.', ' ');
return $remaining;
}
}
}
The point levels are in order in the array, so [0] is $firstlevel, and so on. You simply iterate through the array and return whenever we reach the condition where $point is <= to the the $level.
Also, since $levels is static, it can be defined outside of the function.
simple:
<?php
$point = 100;
$remaining = 0;
$data = [
'firstlevel' => 3000,
'secondlevel' => 7000,
'thirdlevel' => 15000,
'forthlevel' => 28000,
'fifthlevel' => 45000,
'sixthlevel' => 80000
];
foreach($data as $item)
{
if($point <= $item)
{
$remaining = round(($point / $item ) * 100); //or return val
}
}
How about putting your variable into array and loop it?
function to_next_level($point) {
$data[0] = "3000";
$data[1] = "7000";
$data[2] = "15000";
$data[3] = "28000";
$data[4] = "45000";
$data[5] = "80000";
foreach ($data as $key => $value) {
if($point <= $value) {
$total = ($point/$value) * 100;
$remaining = round($total);
return $remaining;
}
}
}
I haven't try it. But it might work for you.
Related to question from this Pearson correlation in PHP , now I'm using that function too for calculate similarity between 2 users with pearson correlation. What I wanna ask is :
I have database name ta_db
And I want to retrieve data from table interest which have 9 attributes into array
After that I want to calculate it with pearson correlation function.
public function similarity($user1, $user2) {
$sharedItem = array();
$pref1 = array();
$pref2 = array();
$result1 = $user1->fetchAllPreferences();
$result2 = $user2->fetchAllPreferences();
foreach($result1 as $pref){
$pref1[$pref->item_id] = $pref->rate;
}
foreach($result2 as $pref){
$pref2[$pref->item_id] = $pref->rate;
}
foreach ($pref1 as $item => $preferenza){
if(key_exists($item,$pref2)){
$sharedItem[$item] = 1;
}
}
$n = count($sharedItem);
if ($n == 0) return 0;
$sum1 = 0;$sum2 = 0;$sumSq1 = 0;$sumSq2 = 0;$pSum = 0;
foreach ($sharedItem as $item_id => $pre) {
$sum1 += $pref1[$item_id];
$sum2 += $pref2[$item_id];
$sumSq1 += pow($pref1[$item_id],2);
$sumSq2 += pow($pref2[$item_id],2);
$pSum += $pref1[$item_id] * $pref2[$item_id];
}
$num = $pSum - (($sum1 * $sum2) / $n);
$den = sqrt(($sumSq1 - pow($sum1,2)/$n) * ($sumSq2 - pow($sum2,2)/$n));
if ($den == 0) return 0;
return $num/$den;
}
From my explanation above, could you please tell me how to retrieve the data into Array? Thank you in advance for your help and clear explanation.
I have an array year_values containing some values like
$year_values = array();
foreach($year_strings as $str) {
$year_values[] = explode(",", $str);
}
then I apply a query for extracting some values from database
$sql = "SELECT inventory.holdingcost as holdingcost,
inventory.ordercost as ordercost, inventory.unitprice as unitprice,
inventory.lead_time as lead_time, items.id as iid
FROM inventory, items
WHERE inventory.item_name = items.item_name";
mysql_error();
$result = mysql_query($sql);
foreach($year_values as $vals) {
while ($row = mysql_fetch_row($result)) {
$w = $row[2];
$e = $row[0];
$r = $row[1];
$tt = $row[3];
$eo = sqrt(2 * $vals[5] * $r / ($e * $w));
$eoq = round($eo, 1);
$ro = $vals[5] / 360;
$rop = round($ro * $tt);
$op = round($vals[5] / $eoq, 1);
$cc = round(89 / $op);
$h = round((($eoq * $e * $w) / 2), 2);
$o = round((($r * $vals[5]) / $eoq), 2);
$z = round($h + $o, 2);
}
}
When I use foreach above while loop it just takes first value of $year_values as $vals[5], I want to make computations inside while for every value of array $year_values.
How to correct it?
repetition is occurring in value1 i.e $val[5] currently:
Value1 Value 2 Value 3
199 202 0.25
199 205 0.25
199 210 0.25
199 230 0.25
1698 202 0.25
1698 205 0.25
1698 210 0.25
1698 230 0.25
instead i want the values to be displayed like
Value1 Value 2 Value 3
199 202 0.25
1698 205 0.25
15 210 0.25
971 230 0.25
I guess you just have to store all your data, so you could reuse it.
$result = mysql_query($sql);
$rows = array() ;
while ($row = mysql_fetch_row($result)){
$rows[] = $row ;
}
foreach($year_values as $vals) {
foreach($rows as $row){
$w = $row[2];
$e = $row[0];
$r = $row[1];
$tt = $row[3];
$eo = sqrt(2 * $vals[5] * $r / ($e * $w));
$eoq = round($eo, 1);
$ro = $vals[5] / 360;
$rop = round($ro * $tt);
$op = round($vals[5] / $eoq, 1);
$cc = round(89 / $op);
$h = round((($eoq * $e * $w) / 2), 2);
$o = round((($r * $vals[5]) / $eoq), 2);
$z = round($h + $o, 2);
}
}
Simply reverse the statements:
while ($row = mysql_fetch_row($result)) {
foreach($year_values as $vals) {
$w = $row[2];
$e = $row[0];
$r = $row[1];
$tt = $row[3];
$eo = sqrt(2 * $vals[5] * $r / ($e * $w));
$eoq = round($eo, 1);
$ro = $vals[5] / 360;
$rop = round($ro * $tt);
$op = round($vals[5] / $eoq, 1);
$cc = round(89 / $op);
$h = round((($eoq * $e * $w) / 2), 2);
$o = round((($r * $vals[5]) / $eoq), 2);
$z = round($h + $o, 2);
}
}
mysql_fetch_row will return false once the rows have been fetched all. To reuse it you should store them in a variable (like the response made by Jari) or you could switch the two cycles (see imulsion's answer)