Looping class, for template engine kind of thing - php

I am updating my class Nesty so it's infinite but I'm having a little trouble.... Here is the class:
<?php
Class Nesty
{
// Class Variables
private $text;
private $data = array();
private $loops = 0;
private $maxLoops = 0;
public function __construct($text,$data = array(),$maxLoops = 5)
{
// Set the class vars
$this->text = $text;
$this->data = $data;
$this->maxLoops = $maxLoops;
}
// Loop function
private function loopThrough($data)
{
if( ($this->loops +1) > $this->maxLoops )
{
die("ERROR: Too many loops!");
}
else
{
$keys = array_keys($data);
for($x = 0; $x < count($keys); $x++)
{
if(is_array($data[$keys[$x]]))
{
$this->loopThrough($data[$keys[$x]]);
}
else
{
return $data[$keys[$x]];
}
}
}
}
// Templater method
public function template()
{
echo $this->loopThrough($this->data);
}
}
?>
Here is the code you would use to create an instance of the class:
<?php
// The nested array
$data = array(
"person" => array(
"name" => "Tom Arnfeld",
"age" => 15
),
"product" => array (
"name" => "Cakes",
"price" => array (
"single" => 59,
"double" => 99
)
),
"other" => "string"
);
// Retreive the template text
$file = "TestData.tpl";
$fp = fopen($file,"r");
$text = fread($fp,filesize($file));
// Create the Nesty object
require_once('Nesty.php');
$nesty = new Nesty($text,$data);
// Save the newly templated text to a variable $message
$message = $nesty->template();
// Print out $message on the page
echo("<pre>".$message."</pre>");
?>
Here is a sample template file:
Dear <!--[person][name]-->,
Thanks for contacting us regarding our <!--[product][name]-->. We will try and get back to you within the next 24 hours.
Please could you reply to this email to certify you will be charged $<!--[product][price][single]--> for the product.
Thanks,
Company.
The problem is that I only seem to get "string" out on the page... :(
Any ideas?

if(is_array($data[$keys[$x]]))
{
$this->loopThrough($data[$keys[$x]]);
}
else
{
return $data[$keys[$x]];
}
You need to return from the first if statement.
if(is_array($data[$keys[$x]]))
{
return $this->loopThrough($data[$keys[$x]]);
}
else
{
return $data[$keys[$x]];
}
This will get you a result back when you recurse. You're only getting "string" back right now because that key is only 1 level deep in your array structure.

Related

PHP how to add a list items inside another list items

I have a list of financial launch. Each launch may or may not have multiple payments. So for every financial launch I look for a list of payments. I would like this list to be within its corresponding financial launch.
My complete function:
public function customerInvoice()
{
$_customer = filtra_int($this->input->post('cliente_id'));
$this->redireciona_id_nula($_customer, $this->url . '/ficha');
$_view = [];
$this->load->helper(['filter', 'string', 'currency', 'validate', 'phone']);
$_view['glyph'] = 'user';
$_view['enterprise'] = $this->enterprise;
$_view['buttons'] = $this->_getFormButtons($_customer, $this->url . '/ficha');
$this->load->model('lancamento_model', 'lancamentoModel');
$_view['releases'] = $this->lancamentoModel->getCustomerRelease($_customer);
foreach ($_view['releases'] as $i => $value) {
// $_view['releases']['order'][$i] = $this->lancamentoModel->getCustomerOrder($value->id);
$value['order'] = $this->lancamentoModel->getCustomerOrder($value->id);
}
$this->addBreadcrumb('Lançamentos', base_url() . 'lancamentos');
$this->addBreadcrumb('Ficha', base_url() . 'lancamentos/ficha');
$this->addBreadcrumb('Exibir');
$this->extras['css'][] = $this->load->view('lancamentos/consulta/ficha_cliente/form/css', null, true);
$this->extras['scripts'][] = $this->load->view('lancamentos/consulta/ficha_cliente/form/js', $_view, true);
// $pagina = $this->getHtmlPagina('Ficha cliente', $_view);
// $this->load->view('lancamentos/consulta/ficha_cliente/view/view', $pagina);
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($_view));
}
json result:
{
"release":{
"0":{
"id":"380",
"data_vcto":"2016-01-15",
"data_emissao":"2016-01-15",
"documento":"292\/1",
"vlr":"67.00",
"vlr_divida":"0.00"
},
"order":[
[
{
"id":"142206",
"data_vcto":"2016-01-15 09:59:24",
"vlr_desconto":"0.00",
"vlr_multa":"0.00",
"pago_em":"2018-11-19 09:59:24",
"conta_nome":"Caixa",
"tipo_nome":"Vendas",
"vlr_movimento":"67.00",
"tipo_pagamento_nome":"Dinheiro"
},
{
"id":"213",
"data_vcto":"2016-01-13 09:59:24",
"vlr_desconto":"0.00",
"vlr_multa":"0.00",
"pago_em":"2018-11-19 09:59:24",
"conta_nome":"Caixa",
"tipo_nome":"Vendas",
"vlr_movimento":"22.00",
"tipo_pagamento_nome":"Dinheiro"
}
]
]
}
}
I would like something like that
{
"release":{
"0":{
"id":"380",
"data_vcto":"2016-01-15",
"data_emissao":"2016-01-15",
"documento":"292\/1",
"vlr":"67.00",
"vlr_divida":"0.00",
"order":[
{
"id":"142206",
"data_vcto":"2016-01-15 09:59:24",
"vlr_desconto":"0.00",
"vlr_multa":"0.00",
"pago_em":"2018-11-19 09:59:24",
"conta_nome":"Caixa",
"tipo_nome":"Vendas",
"vlr_movimento":"67.00",
"tipo_pagamento_nome":"Dinheiro"
},
{
"id":"213",
"data_vcto":"2016-01-13 09:59:24",
"vlr_desconto":"0.00",
"vlr_multa":"0.00",
"pago_em":"2018-11-19 09:59:24",
"conta_nome":"Caixa",
"tipo_nome":"Vendas",
"vlr_movimento":"22.00",
"tipo_pagamento_nome":"Dinheiro"
}
]
}
}
}
it is possible ? And what do I have to do in the foreach?
Update: I did as #Yulio Aleman Jimenez suggested...but after that the error appeared
Fatal error: Cannot use object of type stdClass as array in C:\xampp\htdocs\beauty\application\controllers\Lancamentos.php on line 829
Message: Cannot use object of type stdClass as array
Error Print
I think you must change your code like this:
$_releases = $this->lancamentoModel->getCustomerRelease($_customer);
foreach ($_releases as $i => $value) {
// try with this changes
$value = $this->lancamentoModel->getCustomerOrder($value->id);
$_releases[$i] = (object)array_merge((array)$_releases[$i], array('order' => $value));
}
The thing is to store the array of orders in the order of each release.
Update
You have working with objects, it's the reazon you have to cast to array, add new values in order and then cast to object.

codeigniter - calling two functions from same controller one after the other, second function fails

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();
}
}
?>

Cant pass array value from codeigniter controller to view

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.

how to remove the array to string conversion error in php

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
?>

Get variables from several interrelated functions in PHP

I'm trying to get variables from several interrelated functions during XML parsing and put them into arrays. The code is:
function readChapters($reader) {
while($reader->read()) {
if( /* condition here */ ) {
$chapter = readValue($reader);
}
if( /* condition here */ ) {
readModules($reader);
}
if( /* condition here */ ) {
return;
}
}
}
function readModules($reader) {
while($reader->read()) {
if( /* condition here */ ) {
readModule($reader);
}
if( /* condition here */ ) {
return($reader);
}
}
}
function readModule($reader) {
while($reader->read()) {
if( /* condition here */ ) {
$topic = readValue($reader);
}
if( /* condition here */ ) {
$description = readValue($reader);
}
}
}
function readValue($reader) {
while($reader->read()) {
if( /* condition here */ ) {
return $reader->readInnerXML();
}
}
}
$reader = new XMLReader();
$reader->open('example.xml');
$current = 0;
$topics_list = array();
$chapterName = ""; // want to add $chapter
$topicName = ""; // want to add $topic
$descriptionText = ""; // want to add $description
while($reader->read()) {
if(// condition here) {
readChapters($reader);
}
$topics_list[$current] = array();
$topics_list[$current]['chapter'] = $chapterName;
$topics_list[$current]['topic'] = $topicName;
$topics_list[$current]['description'] = $descriptionText;
}
$reader->close();
print_r($topics_list);
Problem: How to get $chapter, $topic, $description variables from outside of these functions in order to put them into arrays? Thanks in advance.
Update: The XML document structure is here, and the expected structure of Array():
Array (
[0] => Array (
[chapter] => Chapter_name1
[topic] => Topic_name1
[description] => Content_of_the_topic1
)
[1] => Array (
[chapter] => Chapter_name1
[topic] => Topic_name2
[description] => Content_of_the_topic2
)
[2] => Array (
[chapter] => Chapter_name2
[topic] => Topic_name2
[description] => Content_of_the_topic2
)
.....
)
You're essentially using a set of function to build a data structure using data from an XML object. That means that each function should return the data structure it's named for: readChapters() should return a chapter structure (and should probably be named readChapter(), since I think it's only reading one chapter, correct?), and so on. I don't know what your XML looks like or what your desired data structure looks like, but you'll want something like this:
function readChapter($reader) {
$chapter = array();
while (// condition) {
if (// something)
$chapter['chapter'] = readValue($reader);
elseif (// something else)
$chapter['topic'] = readValue($reader);
// etc
}
return $chapter;
}
Then in your main loop below, you can have this:
while ($reader->read()) {
if (// condition here) {
$topics_list[] = readChapter($reader);
}
}
Hope that gets you closer to something you can build!

Categories