How to find difference of same column in foreach loop - codeigniter

I am take all field in for-each loop and take the difference of each two column
enter image description here
The above image 'tech_strt_km' is field name and take the difference of 122-22 and 200-122 how find these difference and store there values in another variyable i am using foreach loop for print these numbers
<?php
foreach($pexpn as $row) {
echo $row->tech_strt_km; ?><br>
} ?>
Any way to find the difference of same column
please help me !!

This should work fine. We add one to the current key to get the next value so we can subtract it from the current value, then we save these differences in an array diff for later usage.
$arr = array('22', '122', '200');
$diff = array();
foreach ($arr as $k => $v) {
if (!isset($arr[$k + 1])) {
// if we don't have a next item we are done
// break from foreach
break;
}
// abs only necessary if we expect negative differences and
// if we don't want that --- store differences in array
// for later usage
$diff[] = abs($arr[$k + 1] - $v);
}
print_r($diff);

Related

see value according to the array

I do a select and get several results in array but I need to get the correct value for each step and set up a condition.
$step = DB::table('records')->where('id_user',$userId)->get();
for($i = 0; $i < count($step); $i++)
{
echo $step[$i]->id_step;
}
Id_step returns me values for each step where on the blade I need to get and see if id_step = 1 is true id_step = 2 is true.
This for is returning me only one value and it has 3 records in the table.
First of all. After a select you get an instance of Eloquent\Collection
Not an array.
So that said to loop do this:
$steps = DB::table('records')->where('id_user',$userId)->get();
foreach($steps as $row) {
echo $row;
}
Since you are familiar with arrays do this:
$steps->toArray();
Now your result is an array
Working insert in view this code.
#for($i = 0; $i < count($step); $i++)
#if($step[$i]->id_step == 2)
working
#else
not working
#endif
#endfor

Eloquent Laravel : creating a counter with foreach loop

using Laravel's Eloquent, I'm trying to add an incremental counter to certain rows based on their 'product_id'.
I thought I could do it like this :
$foos = GanttTask::where('product_id',1)->orderBy('date', 'ASC');
$counter = 1;
foreach($foos as $foo){
$foo->custom_counter = $counter;
$counter +=1;
}
return $foos->get();
But this is of no effect on my data, custom_counter column doesn't change (but I get no error).
I tried to add $foo->save() within my loop with no effect.
Get first all record and then modify single record using save method like this:
$foos = GanttTask::where('product_id',1)->orderBy('date', 'ASC')->get(); // Get All records
$counter = 1;
foreach($foos as $foo){
$foo->custom_counter = $counter;
$counter +=1;
$foo->save(); // Update each record
}
Good Luck !!!
To actually update the database, I reckon you need to persist each data object foo individually not the collection foos as a whole.
$foos = GanttTask::where('product_id',1)->orderBy('date', 'ASC');
$counter = 1;
foreach($foos as $foo){
$foo->custom_counter = $counter;
$counter +=1;
$foo->save(); // Persisting data here
}

Pasting serial numbers to existing entries from a forloop in laravel

I am trying to batch input a number of items, once they are in the database I want to add a unique suffix to the end of the item name. As an example:
[1]Item becomes Item-0001
[2]Item becomes Item-0002 etc....
I have this code at the moment:
$initial = Batches::orderBy('created_at', 'desc')->first();
$batch = Inventory::where('production_id', '=', $initial['batch'])->get();
$production_code = $initial['batch'];
for ($i=0; $i<($data['quantity']); $i++){
$index[]=$i;
}
$batch->each(function ($item, $index) use ($production_code) {
$item->update(['item' => $production_code . '-'.$index]);
});
This works and labels each of the items however it will only add it like so:
Item-0
Item-1
etc..
I would like to find a way to specify the suffix that is added and the starting number, in this case 0001.
Any help would be appreciated.
Thanks
Just add some leading Zeros:
sprintf('%04d', 1); // = 0001
sprintf('%04d', 113); // = 0113
Try to use sprintf() function:
sprintf("%'04d", $index);

Multiple array manipulations and merging

I am an amateur programmer that needs the help of a real one to resolve this beautiful problem, because I must admit that I am really stuck on this one!
In my database I have a « tslines » table that contains a value (sum_week) for a given week(startdate) and a given contract(contract_id)
The fields that are important are : sum_week, user_id , startdate and contract_id
I also have a « users » table, the important values are « first_name, last_name »
I have many workers that have worked on a contract, at different times (startdate, represents the first day of the week)
Example (table below): I can have 3 lines for worker A, and 2 lines for worker B
For some week(startdate), it can happend that no one worked on the contract
I want to show a table with those informations, for contract_id=3(ex) (this field is in tslines table) :
sum_week is a field, I don't want to recalculate with a SQL query
I don’t want to run a query for each weeks to check for each user if he worked on a contract because that would become a problem if I have ex : 30 weeks with 30 users that worked on the project..
I started by building an array of all possible « startdate »
//Selects min and max startdate of the tslines, use $dates->maxdate and ->mindate
$dates = $contract->tslines()->whereIsOfficial(true)->select(DB::raw('MAX(startdate) as maxdate, MIN(startdate) as mindate'))->first();
//Define first date declared in tslines
$loopdate = Carbon::parse($dates->mindate);
$maxdt = Carbon::parse($dates->maxdate);
//While loop to create array of date ranges from min to max
$date_count = 0;
$daterange = array();
while($loopdate->gt($maxdt) == false)
{
$daterange[] = $loopdate->format('Y-m-d');
$loopdate->addDays(7);
$date_count++;
}
I know I have to do some array manipulations but I really don’t know from where to start, even witht the queries..
I can get all the related tslines of contract by doing:
$contract->tslines()->get()
But I dont't know how to build an array that contains user information and all the startdate (even if he didn't work that week)
Can anybody give me some hints.. It would be greatly appreciated!!
Thanks in advance!
Raphaël
Let's start from what we know.
We know which users have worked on which contracts and on what date.
With your function above, we have the max date and the min date a user has started working on a contract.
Solution:
$tslines = $contract->tslines()->orderBy('user_id','ASC')->orderBy('startdate','ASC')->get();
//I didn't see any relationship calls to the user's object, so you'll have to add one of your own. I am assuming, your `tslines` has a relationship `user` here.
$userListResult = $contract->tslines()->with('user')->orderBy('user_id','ASC')->select(\Db::raw('distinct("user_id")')->get();
$dates = $contract->tslines()->whereIsOfficial(true)->select(DB::raw('MAX(startdate) as maxdate, MIN(startdate) as mindate'))->first();
$minDate = Carbon::parse($dates->mindate);
$maxDate = Carbon::parse($dates->maxdate);
//we flatten the array for future use.
$userList = array();
foreach($userListResult as $l)
{
$userList[$l->user_id] = $l->user->first_name.' '.$l->user->last_name;
}
//Assuming you are printing a table in blade
<table>
<?php
//Print the table headers
echo"<tr>
<td>User</td>";
$currDate = clone($minDate);
do
{
echo "<td>".$currDate->format('Y-m-d')."</td>";
$currDate->addDay();
}
while($currDate->diffInDays($maxDate) !== 0);
echo "</tr>";
//Print each user's row
foreach($userlist as $userid => $username)
{
echo "<tr>
<td>
$username
</td>";
$currDate = clone($minDate);
//loop through all the dates in range (min to max date)
do
{
$foundDate = false;
//We check if user has worked on that day
foreach($tslines as $row)
{
if($row->user_id === $userid && $row->startdate->format('Y-m-d') === $currDate->format('Y-m-d'))
{
//Print result if startdate & userid matches
echo "<td>{$row->sum_week}</td>";
$foundDate = true;
//Get out of the loops
break;
}
}
if(!$foundDate)
{
echo "<td>X (didn't work)</td>";
}
$currDate->addDay();
}
while($currDate->diffInDays($maxDate) !== 0);
echo "</tr>";
}
?>
</table>

PHP - How to accomplish this if?

I am creating an order cart.
On the page that displays the cart, it checks if a value stored in the session $order corresponds with an id of a row in a mysql table. If this match exists, then the corresponding row is returned.
Within this process, I am trying to retrieve the quantity value stored in the session $quantity that corresponds to the id of the row in the table.
Each value in $order and $quantityis assigned a name, which is the id of the item they were added from.
This is the code that adds the order to the cart:
if (isset($_POST['action']) and $_POST['action'] == 'Order')
{
// Add item to the end of the $_SESSION['order'] array
$_SESSION['order'][$_POST['id']] = $_POST['id'];
$_SESSION['quantity'][$_POST['id']] = $_POST['quantity'];
header('Location: .');
exit();
}
This is the code on the cart page:
foreach ($order as $item)
foreach ($quantity as $amount)
{
mysql_data_seek( $productsSql, 0); //<- this line, to reset the pointer for every EACH.
while($row = mysql_fetch_assoc($productsSql))
{
$itId = $row['id'];
$itDesc = $row['desc'];
$itPrice1 = $row['price1'];
if ($item == $itId)
{
$pageContent .= '
<tr>
<td>'.$itDesc.'</td>
<td>'.if ($item[''.$itId.''] == $amount[''.$itId.'']) {echo $amount}.'</td>
<td>R'.number_format($itPrice1*$amount, 2).'</td>
</tr>
';
}
}
}
This row is producing a syntax error:
<td>'.if ($item[''.$itId.''] == $amount[''.$itId.'']) {echo $amount}.'</td>
What is the problem here for starters?
Secondly, how would I need to do to accomplish the task that I am facing?
Any input on this would be greatly appreciated!
Could you try this?
<td>'.($item[$itId] == $amount[$itId] ? $amount : '').'</td>
This is a ternary operator, look at http://en.wikipedia.org/wiki/Ternary_operation
You can't simply add conditional statements like that while you're building a string.
You can do this, however
<td>' . ($item[$itId] == $amount[$itId]) ? $amount : null . '</td>
but you should use a more legible method.
Another issue you may get is if $amount is an array, you won't be able to print it as a string. If, however, $amount is an object with ArrayAccess interface, you can print it with the __toString() method; but that's another story.
The code for creating the cart page has several issues.
You walk over items and over quantities, which will probably give you duplicate outputs.
$item is a plain string, so I wonder what $item[$itId] is supposed to do?
You walk over your complete result set several times which actually is not necessary. I really hope that "$productSql" isn't a "select * from product", otherwhise this might get REAL slow in production mode.
I suggest creating a good SQL for getting the data and using this as a basis for filling the page:
// note this has SQL-injection issues, so you really need to make sure that $order contains no crap
$productsSql = mysql_query("select * from product where id in (".join($order, ',').")");
// you now have a result set with all products from your order.
while($row = mysql_fetch_assoc($productsSql))
{
$itId = $row['id'];
$itDesc = $row['desc'];
$itPrice1 = $row['price1'];
// session contains the quantity array mapping ID -> Quantity, so grab it from there
$itQuantity = $quantity[$itId];
// finally calculate the price
$itPrice = number_format($itPrice1*$itQuantity, 2);
// now you have all data for your template and can just insert it.
// if you use double quotes you can put the $xyz into the string directly
$pageContent .= "
<tr>
<td>$itDesc</td>
<td>$itQuanty</td>
<td>R $itPrice</td>
</tr>
";
}

Resources