foreach function not work on CodeIgniter - php

I have problems in function foreach, the resulting data is not showing all
data form database like below table names is "view_kebutuhan_perjal' :
Code In Model
function getPerjal()
{
$query=$this->db->query("SELECT * from view_kebutuhan_perjal");
return $query;
}
Code In Controller :
$Kebutuhan=$this->M_Kebutuhan_Perjal->getPerjal();
foreach ($Kebutuhan->result() as $row ) {
$hasil=array(
$row->id_perjal,
$row->jenis_perjal,
$row->ruas_jalan,
$row->lokasi_km,
$row->letak,
$row->kondisi,
$row->tahun,
$row->tahunRPJMD,
);
}
$data=array(
'data'=> [$hasil],
);
$this->output
->set_status_header(201)
->set_content_type('application/json', 'utf-8')
->set_output(json_encode($data, JSON_PRETTY_PRINT))
->_display();
exit;
But Result data just one record like bellow:-

You are over-writing $hasil variable again and again inside foreach() loop. That's why only one value is coming.Do like below:-
$hasil = array(); // create array variable
foreach ($Kebutuhan->result() as $row ) {
$hasil[]=array(
$row->id_perjal,
$row->jenis_perjal,
$row->ruas_jalan,
$row->lokasi_km,
$row->letak,
$row->kondisi,
$row->tahun,
$row->tahunRPJMD,
); // assign data to array variable
}
$data=array(
'data'=> [$hasil],
);

Related

Larvel Update Data from Array with foreachloop

Hello There I need Help To Update on Vehicle Wies on Specific Dates.I'm Attaching Form image and Here is my Controller code.
public function add_vehicle_expense(Request $request)
{
$veh = array('veh_reg_num' => $request->veh_reg_num);
foreach ($veh as $data) {
print_r($request->date[$data]);
dd();
$veh = Sale_report::where('date',$request->date[$data])->where('veh_reg_num', $request->veh_reg_num[$data])->update(['diesel_qty'=> $request->qty[$data], 'diesel_rate'=> $request->rate[$data], 'diesel_amount'=> $request->total_amount[$data], 'other_expense'=> $request->other_exp[$data]]);
}
if ($veh) {
return redirect()->back()->with('Data Store Successfully');
}
//$veh = Sale_report::where('date',$request->date)->where('veh_reg_num', $request->veh_reg_num)->update(['diesel_qty'=> $request->qty, 'diesel_rate'=> $request->rate, 'diesel_amount'=> $request->total_amount, 'other_expense'=> $request->other_exp]);
/* foreach ($request->date as $reg_num => $key ) {
$s = Sale_report::where('date',$request->date[$reg_num])->where('veh_reg_num',$request->veh_reg_num[$reg_num])->first();
$s->diesel_qty = $request->qty[$reg_num];
$s->diesel_rate = $request->rate[$reg_num];
$s->diesel_amount = $request->total_amount[$reg_num];
$s->other_expense = $request->other_exp[$reg_num];
$s->update();
} */
}
I have try to Update Data by matching Each Vehicle Number with Date Some times it Show ErrorException Attempt to read property on int,ErrorException Undefined array key "data"
I have Found The Solution of this Problem.
I've use implode(',' , $request->veh_reg_num) Then I use $datas = explode() function then I use foreach() With exploded Vairable as foreach($datas as $data => $value){
match the each row that with $data array then I Update the values to data base }

Use Array data in another function

I am hoping I can get some assistance with some issues I'm trying to get the array data from one function to be used in another function.
So in the function that's creating the array data, it looks like this:
function wlp_generate_pdf_and_save( $data, $post_id ){
// Function needing array data
}
function wlp_generate_preview($data, $generateType){
$out_product_brands = array();
if( count($all_posts) > 0 ){
foreach( $all_posts as $s_post )
{
...
$out_product_brands[] = array( 'brand' => vooHelperNew::get_posts_products( $s_post->ID ) );
...
}
}
}
This function "wlp_generate_preview" works perfectly, but it's this $out_product_brands data i need to use in the function (wlp_generate_pdf_and_save) above this one.
Does the order the functions are place change anything?
Return the data from wlp_generate_preview then pass it as a parameter of wlp_generate_pdf_and_save
First you want to return the array from your first function and then send that as a variable to the second function:
<?php
function wlp_generate_pdf_and_save( $data, $post_id, $input_array ){ //added a third
varible to this functions input
// Function needing array data
}
function wlp_generate_preview($data, $generateType){
$out_product_brands = array();
if( count($all_posts) > 0 ){
foreach( $all_posts as $s_post )
{
...
$out_product_brands[] = array( 'brand' => vooHelperNew::get_posts_products( $s_post->ID ) );
...
}
}
return $out_product_brands;//Returned The array
}
And then when calling your functions you might do something like this:
$input_array = wlp_generate_preview($data, $generateType);//Calls the first function
wlp_generate_pdf_and_save($data, $post_id, $input_array);//The third variable passes it into the next function

Store data in a variable from a nested foreach loop from eloquent query statement

I want to pass data from laravel controller to view. the problem i am having is that the data being passed is coming from a database table and its being stored in a variable using nested foreach loop but the variable is being overritten with each loop.
Here is the Code.
public function generateContract(Request $request){
foreach($request->ids as $id){
$contract = explode(",", $id);
$this->techId[] = $contract[0];
$this->meetingId[] = $contract[1];
$this->contractId[] = $contract[2];
}
$names = contract::whereIn('technician_id', $this->techId)->whereIn('meeting_id', $this->meetingId )->get();
foreach($names as $name){
$names_arr[] = $name->firstName;
}
$unique_names = array_unique($names_arr);
foreach($unique_names as $unique_name){
$functions[] = Contract::where('firstName', $unique_name)->whereIn('meeting_id', $this->meetingId)->whereIn('id', $this->contractId)->get();
}
return view('contract.generated_contract', compact('unique_names', 'functions'));
}
My question is how can i pass the $functions variable to view without it being overwritten. I have tried using array but the array is also being overritten with each loop.

PHP Unsetting data in an array

I have the following line which reads a csv and turns each row into an Array
$reader = new CSV\CSVReader('somecsv.csv');
So if I then do
while ($row = $reader->getRow()) {
print "<pre>";
print_r($row);
print "</pre>";
}
It outputs data like so
Array
(
[Column1] => some
[Column2] => data
[Column3] => hi
[Column4] => wow
[Column5] => help
)
Array ...
Say I wanted to remove column1, inside the while loop I can place
unset($row['column1']);
And this will remove column1 from the output. However, if I place a function in my $reader class like so
public function unsetColumns($row)
{
unset($row['column1']);
}
And I change my while loop to the following
while ($row = $reader->getRow()) {
$reader->unsetColumns($row); //this does not work
unset($row['column1']); //this works
print "<pre>";
print_r($row);
print "</pre>";
}
Then the function call does not remove the column, but the unset does. I dont have both in there at the same time, just put them both there so you can see what works and what does not.
Why would this be?
Thanks
You can pass your array by reference read here more on Passing by Reference
public function unsetColumns(&$row)
{
unset($row['column1']);
}
while ($row = $reader->getRow()) {
$reader->unsetColumns($row); //this does not work
unset($row['column1']); //this works
print "<pre>";
print_r($row);
print "</pre>";
}
You are just passing $row, it is getting deleted in function call also.
But, you are not returning it (neither you are passing reference to $row).
Do two changes:
$row = $reader->unsetColumns($row);
And
public function unsetColumns($row)
{
unset($row['column1']);
return $row;
}
So, that your column deletion activity gets used.
You can pass the current $row by reference it to manipulate inside a function and also see those changes outside of that functions scope.
<?php
public function unsetColumns( &$row )
{
unset( $row['column1'] );
}
while( $row = $reader->getRow() ) {
$reader->unsetColumns( $row );
print "<pre>";
print_r($row);
print "</pre>";
}
The difference to your existing code is the additional ampersand in front of the arguments name: &$row in the function declaration.
See: http://php.net/manual/en/language.references.pass.php

PhP Associative Array displayed in a Table

I am VERY new to PhP. Quick question that I am having trouble finding the answer to online, although I am sure most of you will quickly know the answer. I have the following code creating an associative array and then I am trying to display it in a table. I know there are easier ways to display it in a table like a foreach loop, but I would like to learn this method first :
class CarDealer extends Company {
var $navbar_array = array();
function create_navbar_array ( ) {
$mainurl = $this->company_url; // get the main url address of this web page
$this->navbar_array = array( "Home Page"=>"$mainurl?whichpage=home", "Sales"=>"$mainurl?whichpage=sales",
"Support" => "$mainurl?whichpage=support", "Contacts" => "$mainurl?whichpage=contact" );
}
function getLeftNavBar() {
$data ="<table border='1' style='background-color:yellow; width:35%'>";
$data .="<tr><td>$this->navbar_array['Home Page']</td></tr>";
$data .="<tr><td>$this->navbar_array['Sales']</td></tr>";
$data .="<tr><td>$this->navbar_array['Support']</td></tr>";
$data .="<tr><td>$this->navbar_array['Contacts']</td></tr>";
$data .="</table>";
return $data;
}
}
Later in my code I create an object for my class and then try to print the table. Unfortunately I am just getting an output of things like Array['Home Page'].
$carobject = new CarDealer();
$carobject->create_navbar_array();
print $carobject->getLeftNavBar();
you need to pass array values to the function try
class extends Company {
var $navbar_array = array();
function create_navbar_array ( ) {
$mainurl = $this->company_url; // get the main url address of this web page
$this->navbar_array = array( "Home Page"=>"$mainurl?whichpage=home", "Sales"=>"$mainurl?whichpage=sales",
"Support" => "$mainurl?whichpage=support", "Contacts" => "$mainurl?whichpage=contact" );
return $this->navbar_array;
}
function getLeftNavBar($arr) {
$data ="<table border='1' style='background-color:yellow; width:35%'>";
$data .="<tr><td>".$arr['Home Page']."</td></tr>";
$data .="<tr><td>".$arr['Sales']."</td></tr>";
$data .="<tr><td>".$arr['Support']."</td></tr>";
$data .="<tr><td>".$arr['Contacts']."</td></tr>";
$data .="</table>";
return $data;
}
}
$carobject = new CarDealer();
$arr = $carobject->create_navbar_array();
print $carobject->getLeftNavBar($arr);
or need to make public your array
public $navbar_array = array();
before return $data;, print_r($data); so you can know the associative array's structure. If it didnt print on the page, try looking in view-page-source. You'll get an clear picture. I think $data should be an array, so prob it should be like
$data['someField'] = $someValues;
And, Create or define the array before you use them.
You need to concatenate the array values inside the getLeftNavBar() method so php knows to parse them.
try
$data .="<tr><td>{ $this->navbar_array['Home Page'] }</td></tr>";
or
$data .="<tr><td>".$this->navbar_array['Sales']."</td></tr>";
Why not just call create_navbar_array() inside getLeftNavBar()
function getLeftNavBar() {
$this->create_navbar_array();
.....
You could rewrite it like this
class CarDealer {
private function getUrls() {
return array(
"Home Page" => "$this->company_url?whichpage=home",
"Sales" => "$this->company_url?whichpage=sales",
"Support" => "$this->company_url?whichpage=support",
"Contacts" => "$this->company_url?whichpage=contact"
);
}
public function getLeftNavBar() {
$data ="<table border='1' style='background-color:yellow; width:35%'>";
foreach($this->getUrls() as $url ) {
$data .="<tr><td>".$url."</td></tr>";
}
return $data . "</table>";
}
}
$carobject = new CarDealer();
print $carobject->getLeftNavBar();

Categories