Related
This one's got me stuck!
I have two functions in a controller which can be called from a menu independantly and they work fine.
I want to call them in a month end routine (in the same controller), one after the other; the first function works fine and returns to the calling function, the second function is called but fails because the load of the $model variable fails.
Here is the code for the month end routine,
function month_end_routines()
{
// create stock inventory valuation report in excel format
$export_excel = 1;
$this -> inventory_summary($export_excel);
// create negative stock
$export_excel = 1;
$this -> inventory_negative_stock($export_excel);
echo 'debug 2';
// reset rolling inventory indicator
$this -> load->model('Item');
$this -> load->library('../controllers/items');
$this -> items->reset_rolling();
}
Here is the code for the first function called inventory_summary,
function inventory_summary($export_excel=0, $create_PO=0, $set_NM=0, $set_SM=0)
{
// load appropriate models and libraries
$this -> load->model('reports/Inventory_summary');
$this -> load->library('../controllers/items');
// set variables
$model = $this->Inventory_summary;
$tabular_data = array();
$edit_file = 'items/view/';
$width = $this->items->get_form_width();
$stock_total = 0;
// get all items
$report_data = $model->getData(array());
foreach($report_data as $row)
{
$stock_value = $row['cost_price'] * $row['quantity'];
$stock_total = $stock_total + $stock_value;
// set up the item_number to handle blanks
if ($row['item_number'] == NULL) {$row['item_number'] = $this->lang->line('common_edit');}
$tabular_data[] = array (
$row['category'],
anchor (
$edit_file.$row['item_id'].'/width:'.$width,
$row['item_number'],
array('class'=>'thickbox','title'=>$this->lang->line('items_update'))
),
$row['reorder_policy'],
$row['name'],
$row['cost_price'],
$row['quantity'],
$stock_value,
$stock_total
);
}
$today_date = date('d/m/Y; H:i:s', time());
$data = array (
"title" => $this->lang->line('reports_inventory_summary_report'),
"subtitle" => ' - '.$today_date.' '.$this->lang->line('common_for').' '.$this->db->database.'.',
"headers" => $model->getDataColumns(),
"data" => $tabular_data,
"summary_data" => $model->getSummaryData(array()),
"export_excel" => $export_excel
);
if ($export_excel == 1)
{
$this->load->model('Common_routines');
$this->Common_routines->create_csv($data);
}
else
{
$this->load->view("reports/tabular", $data);
}
return;
.. and here is the code for the second function,
function inventory_negative_stock($export_excel=0, $create_PO=0, $set_NM=0, $set_SM=0)
{
echo 'debug 1.5';
$this -> load->model('reports/Inventory_negative_stock');
$this -> load->library('../controllers/items');
echo 'debug 1.6';
$model = $this->Inventory_negative_stock;
var_dump($model);
$tabular_data = array();
$edit_file = 'items/view/';
$width = $this->items->get_form_width();
echo 'debug 1.7';
$report_data = $model->getData(array());
echo 'debug 1.8';
foreach($report_data as $row)
{
// set up the item_number to handle blanks
if ($row['item_number'] == NULL) {$row['item_number'] = $this->lang->line('common_edit');}
// load each line to the output array
$tabular_data[] = array(
$row['category'],
anchor (
$edit_file.$row['item_id'].'/width:'.$width,
$row['item_number'],
array('class'=>'thickbox','title'=>$this->lang->line('items_update'))
),
$row['name'],
$row['cost_price'],
$row['quantity']
);
}
// load data array for display
$today_date = date('d/m/Y; H:i:s', time());
$data = array (
"title" => $this->lang->line('reports_negative_stock'),
"subtitle" => ' - '.$today_date.' '.$this->lang->line('common_for').' '.$this->db->database.'.',
"headers" => $model->getDataColumns(),
"data" => $tabular_data,
"summary_data" => $model->getSummaryData(array()),
"export_excel" => $export_excel
);
if ($export_excel == 1)
{
$this->load->model('Common_routines');
$this->Common_routines->create_csv($data);
}
else
{
$this->load->view("reports/tabular", $data);
}
return;
}
This line is failing
$model=$this->Inventory_negative_stock;
In the first function $model is loaded correctly. In the second it isn't.
It does not matter in which order these functions are called; $model always fails to load in the second function called.
Any help would be great and thanks in advance. I hope I've given enough code; if you need more information let me know.
As requested, here is the code in Inventory_negative_stock,
<?php
require_once("report.php");
class Inventory_negative_stock extends Report
{
function __construct()
{
parent::__construct();
}
public function getDataColumns()
{
return array (
$this->lang->line('reports_category'),
$this->lang->line('reports_item_number'),
$this->lang->line('reports_item_name'),
$this->lang->line('reports_cost_price'),
$this->lang->line('reports_count')
);
}
public function getData(array $inputs)
{
$this->db->select('category, name, cost_price, quantity, reorder_level, reorder_quantity, item_id, item_number');
$this->db->from('items');
$this->db->where("quantity < 0 and deleted = 0");
$this->db->order_by('category, name');
return $this->db->get()->result_array();
}
public function getSummaryData(array $inputs)
{
return array();
}
}
?>
After looking for a built in function in php I couldn't find a similar function to Excel's vlookup function.
I need a function that takes in an array and a lookup value and return the required info. So for example:
<?php
$baseCalculationPrice = [
0 => 50, //for values <=500 but >0
500 => 18, //for values <=3000 but >500
3000 => 15, //for values <=5000 but >3000
5000 => 14, //for values >5000
];
//Examples
$numPages = 499;
echo vlookup($numPages,$baseCalculationPrice); //should output 50
$numPages = 500;
echo vlookup($numPages,$baseCalculationPrice); //should output 50
$numPages = 501;
echo vlookup($numPages,$baseCalculationPrice); //should output 18
$numPages = 3000;
echo vlookup($numPages,$baseCalculationPrice); //should output 18
$numPages = 3001;
echo vlookup($numPages,$baseCalculationPrice); //should output 15
$numPages = 5000;
echo vlookup($numPages,$baseCalculationPrice); //should output 15
$numPages = 5001;
echo vlookup($numPages,$baseCalculationPrice); //should output 14
function vlookup($value,$array){
//magic code
return ....;
}
?>
I'm stuck even with the logic behind such a function, so any help would be great - thanks.
function vlookup($lookupValue,$array){
$result;
//test each set against the $lookupValue variable,
//and set/reset the $result value
foreach($array as $key => $value)
{
if($lookupValue > $key)
{
$result = $value;
}
}
return $result;
}
function testDeductionRate(){echo $this->deductionRate('ks',300);//zone and time are parameter for deductionRate() }
//deduction will be acted as vlookup (rangeLookup true)
function deductionRate($zone,$time){
$actualRate = 0;
$allRate = array(
'tg'=>array(0=>0,20=>200,30=>300,40=>400,50=>500),
'ks'=>array(0=>0,20=>100,30=>200,40=>300,50=>400),
'pc'=>array(0=>0,20=>50,30=>100,40=>200,50=>300)
);
if(isset($allRate[$zone])){
$rate = $allRate[$zone];
foreach($rate as $key=>$val){
if($time>=$key) $actualRate = $val;
}
}else{
return -1; //-1 means error
}
return $actualRate;
}
Try this if you would like to query on multi dimension associative array:
function vlookup($lookup_vakue, $lookup_array, $lookup_column, $result_column)
{
foreach ($lookup_array as $item) {
if ($item[$lookup_column] == $lookup_vakue) {
return $item[$result_column];
}
}
return false;
}
Sample Data
$data =
[
['id'=>1,'price'=>100],
['id'=>2,'price'=>200],
['id'=>3,'price'=>300]
];
Query Option
$result = vlookup('2',$data, 'id','price');
Result:
200
$getbase= function($amount) use ($baseCalculationPrice)
{
return (end(array_filter(
$baseCalculationPrice,function ($key) use ($amount)
{
return $key < $amount;
},
ARRAY_FILTER_USE_KEY
)));
};
amount 150 result 50
amount 1500 result 18
amount 25000 result 14
I am trying to use json encode for the first time and need some insight to what I am doing wrong.
It should look like this:
{ teams : [ ["2147483647", "9"],["2147483647", "6"],["2147483647", "4"],["11", "2147483647"],["5", "2147483647"],["12", "8"],["10", "3"],["2147483647", "7"], ], results : [ [ [[0, 1],[0, 1],[0, 1],[1, 0],[1, 0],[0, 0],[0, 0],[0, 1],], [[0, 0],[0, 0],[0, 0],[0, 0],], [[0, 0],[0, 0],], [[0, 0],[0, 0]] ] ] }
But the data being returned looks like this:-
{"teams":[["2147483647","10","5","12","11","2147483647","2147483647","2147483647"],["7","3","2147483647","8","2147483647","4","6","9"]],"results":[["0","0","0","0","0","0","0","0"],["0","0","0","0","0","0","0","0"]]}
Code:
public function getAutoCompleteData($tournID, $db)
{
$max = $this->max($tournID);
$one = $this->tourn_info("1on1", $tournID);
$total_matches = $max;
$after_matches = $max / 2;
$matches = $db->query($this->select("*", "matches", "leagueID='{$tournID}' AND league='tourn'"));
while ($row = $db->fetchAssoc($matches)) {
$clan1 = $this->getname($row['clan1'], $tournID, "tourn", $ac = NULL, 1, 1, $wc2 = 0);
$clan2 = $this->getname($row['clan2'], $tournID, "tourn", $ac = NULL, 1, 1, $wc2 = 1);
if ($row['matchno'] <= $after_matches) {
$clan_one[] = $row['clan1'];
$clan_two[] = $row['clan2'];
$score_one[] = $row['score1'];
$score_two[] = $row['score2'];
}
}
$data = array(
'teams' => array(
$clan_one,
$clan_two
),
'results' => array(
$score_one,
$score_two
)
);
return $data;
}
Where it shows teams, it should close the bracket ] every two teams?
Hope someone can help.
Not saying this will fix your problem, but it may help you to understand PHP.
class mustBeAClass{
protected function max($tnid){
// must have this function - can be public for outside method use
}
protected function tourn_info($typ, $tnid){
// must have this function - can be public for outside method use
}
protected function getname($arg0, $arg1, $arg2, $arg3, $arg4, $arg5, $arg6 = 0){
/* must have this function - can be public for outside method use
notice that $arg6 is how you assign default to arguments */
}
public function getAutoCompleteData($tournID, $db){
$db->open();
$max = $this->max($tournID); $one = $this->tourn_info("1on1", $tournID);
// what is the point of this ---->>>> $total_matches = $max;
$after_matches = $max / 2;
// notice query issue below
$matches = $db->query("SELECT * FROM matches WHERE leagueID ='$tournID' && league='tourn'"));
// while loop has problems
if($matches->num_rows < 1){
die('You have no matches');
}
else{
while($row = $db->fetch_assoc()){
$clan1 = $this->getname($row['clan1'], $tournID, 'tourn', null, 1, 1, 0);
$clan2 = $this->getname($row['clan2'], $tournID, 'tourn', null, 1, 1, 1);
if($row['matchno'] <= $after_matches) {
$clan_one[] = $row['clan1'];
$clan_two[] = $row['clan2'];
$score_one[] = $row['score1'];
$score_two[] = $row['score2'];
}
}
$data = array(
'teams' => array($clan_one, $clan_two),
'results' => array($score_one, $score_two)
);
}
$matches->free(); $db->close();
return $data;
}
}
$cls = new mustBeAClass;
echo json_encode($cls->getAutoCompleteData($tournId, $db));
Of course use the correct values for $tournId and your new mysqli(/*args*/) for $db.
Inside my controller, I have a line that needs to pass $content['pass_check'] to the view. It is inside an if statement that checks for validation. This I have found causes it to break. Once I move the $content['pass_check'] outside of any if statement, it works just fine passing to the view. All of the other values are passed (accounts, expense_accounts, vendors, terms). What must I do to get it to pass within this if statement. I've even tried moving it outside of the validation and it still wont set.
function create() {
require_permission("INVOICE_EDIT");
$this->load->library("form_validation");
$this->form_validation->set_rules("invoice_number", "Invoice Number", "required");
if($this->form_validation->run() !== false) {
$post = $this->input->post();
$this->session->set_userdata("create_invoice_vendor", $post['vendor_id']);
$this->session->set_userdata("create_invoice_date", $post['invoice_date']);
$invoice_number_exists = $this->invoices->count(array("invoice_number" => $post['invoice_number'])) > 0;
$post['invoice_date'] = date("Y-m-d", strtotime($post['invoice_date']));
$post['due_date'] = date("Y-m-d", strtotime($post['due_date']));
$post['date_entered'] = "now()";
$id = $this->invoices->insert_invoice($post);
$this->load->model("vendors");
if(isset($post['invoice_number'])){
$string_check= $post['invoice_number'];
$string_check= preg_replace('/\d/', '#', $string_check);
$string_check= preg_replace('/\w/', '#', $string_check);
$invoice_pattern=array();
$invoice_pattern = $this->db->select("invoice_pattern")->where("vendor_id",
$post['vendor_id'])->get("vendors")->result();
$invoice_pattern=$invoice_pattern[0]->invoice_pattern;
* //// THIS IS WHERE I NEED HELP ///////
if($invoice_pattern == $string_check){
***$content['post_check'] = 1;***
$this->invoices->flag_invoice($id);
};
};
$history = array(
"type" => "invoice_entered",
"comments" => "Invoice was entered",
"link" => $id,
"admin_id" => $this->user->admin_id,
"date" => "now()",
);
$this->vendors->insert_history($post['vendor_id'], $history);
if($post['flagged'] == 1) {
$this->invoices->flag_invoice($id);
}
if($invoice_number_exists) {
redirect("invoices/confirm_invoice/".$id);
} else {
// redirect("invoices/view/".$id);
redirect("invoices/create");
}
}
$content['accounts'] = $this->db->get("acct_chart_of_accounts")->result();
$content['expense_accounts'] = $this->db->get("invoice_expense_accounts")->result();
$content['vendors'] = $this->db->select("vendor_id, name, terms, override, invoice_pattern")
->order_by("name ASC")->get("vendors")->result();
$content['terms'] = $this->db->query("SELECT DISTINCT(terms) FROM vendors")->result();
}
}
$this->template['sub_heading'] = "Create";
$this->template['content'] = $this->load->view("invoices/create", $content, true);
$this->template['sidebar'] = $this->load->view("invoices/sidebar", array(), true);
$this->template['scripts'] = array("codeigniter/javascript/invoices/create.js");
$this->template['styles'][] = "codeigniter/styles/invoices/create.css";
$this->display();
}
Obviously it won't pass it to the view if the condition doesn't match, because you're only declaring the variable within the condition if it matches.
Just create $content['pass_check'] with an initial value of 0 or whatever before the conditional check first.
function create() {
...snip...
$content['pass_check'] = 0;
if($invoice_pattern == $string_check) {
$content['post_check'] = 1;
$this->invoices->flag_invoice($id);
};
...snip...
}
Let me know if this works or not please.
i am working on php i have dynamic array i need to get the array result store in some variable i encounter the error :array to string conversion
coding
<?php
require_once('ag.php');
class H
{
var $Voltage;
var $Number;
var $Duration;
function H($Voltage=0,$Number=0,$Duration=0)
{
$this->Voltage = $Voltage;
$this->Number = $Number;
$this->Duration = $Duration;
}}
//This will be the crossover function. Is just the average of all properties.
function avg($a,$b) {
return round(($a*2+$b*2)/2);
}
//This will be the mutation function. Just increments the property.
function inc($x)
{
return $x+1*2;
}
//This will be the fitness function. Is just the sum of all properties.
function debug($x)
{
echo "<pre style='border: 1px solid black'>";
print_r($x);
echo '</pre>';
}
//This will be the fitness function. Is just the sum of all properties.
function total($obj)
{
return $obj->Voltage*(-2) + $obj->Number*2 + $obj->Duration*1;
}
$asma=array();
for($i=0;$i<$row_count;$i++)
{
$adam = new H($fa1[$i],$fb1[$i],$fcc1[$i]);
$eve = new H($fe1[$i],$ff1[$i],$fg1[$i]);
$eve1 = new H($fi1[$i],$fj1[$i],$fk1[$i]);
$ga = new GA();
echo "Input";
$ga->population = array($adam,$eve,$eve1);
debug($ga->population);
$ga->fitness_function = 'total'; //Uses the 'total' function as fitness function
$ga->num_couples = 5; //4 couples per generation (when possible)
$ga->death_rate = 0; //No kills per generation
$ga->generations = 10; //Executes 100 generations
$ga->crossover_functions = 'avg'; //Uses the 'avg' function as crossover function
$ga->mutation_function = 'inc'; //Uses the 'inc' function as mutation function
$ga->mutation_rate = 20; //10% mutation rate
$ga->evolve(); //Run
echo "BEST SELECTED POPULATION";
debug(GA::select($ga->population,'total',3)); //The best
$array=array((GA::select($ga->population,'total',3))); //The best }
?>
<?php
$comma_separated = implode(",", $array);
echo $comma_separated; // lastname,email,phone
?
>
i apply implode function but its not working
it display the error of : Array to string conversion in C:\wamp\www\EMS3\ge.php on line 146 at line $r=implode($rt,",");
<script>
if ( ($textboxB.val)==31.41)
{
</script>
<?php echo "as,dll;g;h;'islamabad"; ?>
<script>} </script>
You are running your java script code in PHP, I havent implemented your code just checked and found this bug.You can get the value by submitting the form also
---------------------------- Answer For your Second updated question------------------------
<?php
$array = array(
"name" => "John",
"surname" => "Doe",
"email" => "j.doe#intelligence.gov"
);
$comma_separated = implode(",", $array); // You can implode them with any character like i did with ,
echo $comma_separated; // lastname,email,phone
?>