Multidimensional arrays and for loops - arrays

i have this code >
if ($firstDayOfTheMonth == "Monday")
{
$eachDay["monday1"]="1st";
$eachDay["tuesday1"]="2nd";
$eachDay["wednesday1"]="3rd";
$eachDay["thursday1"]="4th";
$eachDay["friday1"]="5th";
$eachDay["saturday1"]="6th";
$eachDay["sunday1"]="7th";
$eachDay["monday2"]="8th";
$eachDay["tuesday2"]="9th";
$eachDay["wednesday2"]="10th";
$eachDay["thursday2"]="11th";
$eachDay["friday2"]="12th";
$eachDay["saturday2"]="13th";
$eachDay["sunday2"]="14th";
$eachDay["monday3"]="15th";
$eachDay["tuesday3"]="16th";
$eachDay["wednesday3"]="17th";
$eachDay["thursday3"]="18th";
$eachDay["friday3"]="19th";
$eachDay["saturday3"]="20th";
$eachDay["sunday3"]="21st";
$eachDay["monday4"]="22nd";
$eachDay["tuesday4"]="23rd";
$eachDay["wednesday4"]="24th";
$eachDay["thursday4"]="25th";
$eachDay["friday4"]="26th";
$eachDay["saturday4"]="27th";
$eachDay["sunday4"]="28th";
$eachDay["monday5"]="29th";
$eachDay["tuesday5"]="30th";
$eachDay["wednesday5"]="31st";
}
and i wondered if anyone could help me condense it down into a loop?
The code is far too long and messy and i would love to shorten it down

One probable implementation assuming its perl
use strict;
sub dayHash {
my $firstDayOfMonth = lc(shift);
my #days = qw(monday tuesday wednesday thursday friday saturday sunday);
my $start = -1;
my $i;
for ( $i = 0; $i < $#days; $i++ ) {
if ( $firstDayOfMonth eq $days[$i] ) {
$start = $i;
last;
}
}
my %eachDay = ();
my $suffix = 1;
my $key;
my $val;
for ( $i = 1; $i <= 31; $i++ ) {
$key = "$days[$start++]$suffix";
if ( $start > $#days ) {
$start = 0;
$suffix++;
}
if ( ($i % 10) == 1 && int($i / 10) != 1 ) {
$val = $i. 'st';
} elsif ( ($i % 10) == 2 && int($i / 10) != 1 ) {
$val = $i . 'nd';
} elsif ( ($i % 10) == 3 && int($i / 10) != 1 ) {
$val = $i . 'rd';
} else {
$val = $i . 'th';
}
$eachDay{$key} = $val;
}
return %eachDay
}
my $firstDayOfMonth = "Monday";
my %eachDay = dayHash($firstDayOfMonth);

Related

sqlsrv_fetch_array() expects parameter 1 to be resource, object given

Good Day,
I was looking for the solution of this code. But unfortunately I couldn`t fix it hope someone can enlighten me on this matter.
function getCharactersBySerial($serial)
{
$charinfo = "";
$i = 0;
$CI =& get_instance();
$CI->mssql = $CI->load->database( 'world', TRUE );
$char_result = $CI->mssql->query("SELECT * FROM RF_World.dbo.tbl_base WHERE Serial= $serial and DCK='0'");
while ($character = sqlsrv_fetch_array($char_result))
{
$charinfo['Serial'] = $character['Serial'];
$charinfo['Name'] = $character['Name'];
$charinfo['AccountSerial'] = $character['AccountSerial'];
$i = 1;
return $charinfo;
}
if ($i == 0 ) {
return "None";
}
}
and this is the other one they have both same errors
function getCharactersGuildBySerial($serial)
{
$charinfo = "";
$i = 0;
$CI =& get_instance();
$CI->mssql = $CI->load->database( 'world', TRUE );
$char_result = $CI->mssql->query("SELECT B.Name, L.id FROM tbl_base as B INNER JOIN tbl_general as G ON G.Serial = B.Serial INNER JOIN tbl_Guild as L ON L.Serial = G.GuildSerial WHERE B.Serial= $serial and B.DCK='0'");
while ($character = sqlsrv_fetch_array($char_result))
{
$charinfo['GuildName'] = $character['id'];
$charinfo['Name'] = $character['Name'];
$i = 1;
return $charinfo;
}
if ($i == 0 ) {
$charinfo['Name'] = 'None';
return $charinfo;
}
}
I just fund out the error was because of my Condition and it only appears if the query doesn`t have a result. Please check below for the fix that I did:
function getCharactersBySerial($serial)
{
$charinfo = "";
$i = 0;
$CI =& get_instance();
$CI->mssql = $CI->load->database( 'world', TRUE );
$char_result = $CI->mssql->query("SELECT * FROM RF_World.dbo.tbl_base WHERE Serial= $serial and DCK='0'");
if($char_result->num_rows()<=0){
return 'None';
}else{
while ($character = sqlsrv_fetch_array($char_result))
{
$charinfo['Serial'] = $character['Serial'];
$charinfo['Name'] = $character['Name'];
$charinfo['AccountSerial'] = $character['AccountSerial'];
$i = 1;
return $charinfo;
}
}
}
and
function getCharactersGuildBySerial($serial)
{
$charinfo = "";
$i = 0;
$CI =& get_instance();
$CI->mssql = $CI->load->database( 'world', TRUE );
$char_result = $CI->mssql->query("SELECT B.Name, L.id FROM tbl_base as B INNER JOIN tbl_general as G ON G.Serial = B.Serial INNER JOIN tbl_Guild as L ON L.Serial = G.GuildSerial WHERE B.Serial= $serial and B.DCK='0'");
if($char_result->num_rows()<=0){
$charinfo['Name'] = 'None';
return $charinfo;
}else{
while ($character = sqlsrv_fetch_array($char_result))
{
$charinfo['GuildName'] = $character['id'];
$charinfo['Name'] = $character['Name'];
$i = 1;
return $charinfo;
}
}
}

How to update main array in laravel

I Need help on updating Main Array with its data changed in a foreach loop.
Here is my code :
$query = DB::table('autostk')
->where('autostk.branchid', $branch_id)
->where('autostk.itemcode', $request->itemcode)
->whereDate('autostk.date', '<=', $request->tdate)
->where('autostk.branchid', $branch_id)
->leftjoin('journal', 'autostk.refno', '=', 'journal.vno')
->where('journal.code', '>=', 100)
->where('journal.branchid', $branch_id)
->leftjoin('accounts', 'journal.code', '=', 'accounts.code')
->where('accounts.branchid', $branch_id)
->select('journal.code', 'accounts.title', 'autostk.*')
->orderBY('date')->get()
->map(function ($item, $key) {
return (array)$item;
})
->all();
foreach ($query as $row) {
if (is_null($row['qtyin'])) {
$row['qtyin'] = 0;
}
if (is_null($row['qtyout'])) {
$row['qtyout'] = 0;
}
if (is_null($row['rate'])) {
$row['rate'] = 0;
}
if ($row['vtype'] = 'PI' && $row['qtyin'] > 0) {
$stkval = ($bal * $avgrate) + ($row['qtyin'] * $row['rate']);
if ($bal > 0) {
$bal = $bal + $row['qtyin'] - $row['qtyout'];
if ($bal > 0 && $stkval > 0) {
$avgrate = $stkval / $bal;
}
} else {
$bal = $bal + $row['qtyin'] - $row['qtyout'];
$avgrate = $row['rate'];
}
} else {
$bal = $bal + $row['qtyin'] - $row['qtyout'];
}
$row['balqty'] = $bal;
$row['avgrate'] = $avgrate;
}
My question is how to update $query with changes made to $row. I am new to php and laravel and have tried push(), put(), etc. Don't know which function is required in this case.
To keep changes you've applied to $row inside the foreach you just need to pass it by reference:
foreach ($query as &$row) { //notice the & before $row
Alternatively, you could could use just move the code inside your foreach to inside your map closure:
->map(function ($item, $key) use ($bal, $avgrate) {
$row = (array)$item;
if (is_null($row['qtyin'])) {
$row['qtyin'] = 0;
}
if (is_null($row['qtyout'])) {
$row['qtyout'] = 0;
}
if (is_null($row['rate'])) {
$row['rate'] = 0;
}
if ($row['vtype'] = 'PI' && $row['qtyin'] > 0) {
$stkval = ($bal * $avgrate) + ($row['qtyin'] * $row['rate']);
if ($bal > 0) {
$bal = $bal + $row['qtyin'] - $row['qtyout'];
if ($bal > 0 && $stkval > 0) {
$avgrate = $stkval / $bal;
}
} else {
$bal = $bal + $row['qtyin'] - $row['qtyout'];
$avgrate = $row['rate'];
}
} else {
$bal = $bal + $row['qtyin'] - $row['qtyout'];
}
$row['balqty'] = $bal;
$row['avgrate'] = $avgrate;
return $row;
})
Try following code:
$query = DB::table('autostk')
->where('autostk.branchid', $branch_id)
->where('autostk.itemcode', $request->itemcode)
->whereDate('autostk.date', '<=', $request->tdate)
->where('autostk.branchid', $branch_id)
->leftjoin('journal', 'autostk.refno', '=', 'journal.vno')
->where('journal.code', '>=', 100)
->where('journal.branchid', $branch_id)
->leftjoin('accounts', 'journal.code', '=', 'accounts.code')
->where('accounts.branchid', $branch_id)
->select('journal.code', 'accounts.title', 'autostk.*')
->orderBY('date')->get()
->map(function ($item, $key) {
return (array)$item;
})
->all();
$row_data = [];
foreach ($query as $row) {
if (is_null($row['qtyin'])) {
$row['qtyin'] = 0;
}
if (is_null($row['qtyout'])) {
$row['qtyout'] = 0;
}
if (is_null($row['rate'])) {
$row['rate'] = 0;
}
if ($row['vtype'] = 'PI' && $row['qtyin'] > 0) {
$stkval = ($bal * $avgrate) + ($row['qtyin'] * $row['rate']);
if ($bal > 0) {
$bal = $bal + $row['qtyin'] - $row['qtyout'];
if ($bal > 0 && $stkval > 0) {
$avgrate = $stkval / $bal;
}
} else {
$bal = $bal + $row['qtyin'] - $row['qtyout'];
$avgrate = $row['rate'];
}
} else {
$bal = $bal + $row['qtyin'] - $row['qtyout'];
}
$row['balqty'] = $bal;
$row['avgrate'] = $avgrate;
$row_data[] = $row;
}
Now use $row_data.
Option 1
//use toArray() in last to get the result as an array
$query = ...->all()->toArray();
foreach ($query as $key => $row) {
//inside here instead of using $row, use $query[$key]
//so for example $row['rate'] = 0; becomes:
$query[$key]['rate'] = 0;
}
Option 2
//use toArray() in last to get the result as an array
$query = ...->all()->toArray();
//use pass by reference with help of &
foreach ($query as $key => &$row) {
...
}
However, be very careful with a pass by reference approach otherwise you might run into issues if you reuse the same array.
Option 3
$query = ...->all();
foreach ($query as $key => $row) {
//access it as object
//instead of using $row['qtyin'] use:
$row->qtyin = 0;
}
Its dealer's choice :)

Get minimum value in an array and then get index

I want to get the minimum value in an array and then get the index of that item, in one step without writing my own loop (if I have to please let me know).
I know I can just do the
$b = ($a | Measure -Minimum).Minimum
But then I have to do
[array]::IndexOf($a, $b)
And while that is normally okay, I'm looking for a way to do it once because I'm running this MANY MANY times in a loop.
Thanks!
EDIT: One step meaning without looping through the array twice
Personally, I might consider a different data structure. Maybe something sorted to begin with...
This code may work for your needs:
$myArray = 5,66,4,33,2,9,9,12
$index = 0
$minIndex = 0
$minValue = [int]::MaxValue
$myArray | % { if ($minValue -gt $_) {$minValue = $_; $minIndex = $index}; $index++ }
"MinIndex $minIndex = MinValue $minValue"
its a problem of type, try like this:
$myArray = [int[]]5,66,4,33,2,9,9,12
$minvalue=[int]($myArray | measure -Minimum).Minimum
$myArray.IndexOf($minvalue)
Here are 6 different options for you...
cls
$myArray = #(5,66,4,33,2,9,9,12)
$iterations = 50000
$t = (measure-command{
foreach ($i in 1..$iterations) {
$minValue = [int]($myArray | Measure-Object -Minimum).Minimum
$minIndex = $myArray.IndexOf($minValue)
}
}).TotalSeconds
"measure-object with indexOf: $t"
$t = (measure-command{
foreach ($i in 1..$iterations) {
$index = 0
$minIndex = 0
$minValue = [int]::MaxValue
$myArray | % { if ($minValue -gt $_) {$minValue = $_; $minIndex = $index}; $index++ }
}
}).TotalSeconds
"pipeline with compare: $t"
$t = (measure-command{
foreach ($i in 1..$iterations) {
$minIndex = 0
$minValue = [int]::MaxValue
foreach ($index in 0..($myArray.count-1)) {
if ($myArray[$index] -lt $minValue) {
$minValue = $myArray[$index]
$minIndex = $index
}
}
}
}).TotalSeconds
"foreach-loop with compare: $t"
$t = (measure-command{
foreach ($i in 1..$iterations) {
$h = [System.Collections.ArrayList]::new()
foreach ($index in 0..($myArray.count-1)) {
$null = $h.add([tuple]::Create($myArray[$index], $index))
}
$h.Sort()
$minIndex = $h[0].Item2
}
}).TotalSeconds
"quicksort of a list of tuples: $t"
Add-Type -TypeDefinition #"
using System;
using System.Linq;
public static class My {
public static int indexOfMin(int[] arr){
int min = arr.Min();
return Array.IndexOf(arr, min);
}
}
"#
$t = (measure-command{
foreach ($i in 1..$iterations) {
$minIndex = [my]::indexOfMin($myArray)
}
}).TotalSeconds
"custom type and IndexOf: $t"
Add-Type #"
public static int[] indexOfMin(int[] arr){
int min = int.MaxValue;
int minIndex = 0;
for (int i = 0; i < arr.Length; i++) {
if (arr[i]<min) {
min = arr[i];
minIndex = i;
}
}
return new int[] {min, minIndex};
}
"# -name My2 -Namespace System
$t = (measure-command{
foreach ($i in 1..$iterations) {
$minValue, $minIndex = [my2]::indexOfMin($myArray)
}
}).TotalSeconds
"custom type and looping: $t"

Do - while loop stops when condition is not finished

I need to copy a two-dimensional array into a second, identically-sized array, but the while loops finishes before I want it to, and I don't know why.
Here is my code.
memcpy( array2, array1, sizeof(array1) );
do
{
for( i = 0; i < rows; i++ )
{
for( j = 0; j < columns; j++ )
{
if( array1[i][j] == '!' )
{
if( array1[(i + 1)][j] == 'o' )
{
array2[(i + 1)][j] = '!';
condition1 = 1;
}
else
{
condition1 = 0;
}
if( array1[(i - 1)][j] == 'o' )
{
array2[(i - 1)][j] = '!';
condition2 = 1;
}
else
{
condition2 = 0;
}
if( array1[i][(j + 1)] == 'o' )
{
array2[i][(j + 1)] = '!';
contidion3 = 1;
}
else
{
condition3 = 0;
}
if( array1[i][(j - 1)] == 'o' )
{
array2[i][(j - 1)] = '!';
condition4 = 1;
}
else
{
condition4 = 0;
}
}
}
}
memcpy( array1, array2, sizeof(array2) );
count++;
}
while( condition1 != 0 && condition2 != 0 && condition3 != 0 && condition4 != 0 );
I've checked the state of each of the 4 condition variables, but every time I print them out I recieve 1 for all of them. I will be grateful for any advice.

How can I display the max value array, edited in a class

I need to find the worker with highest salary in PHP and display only him (his name, position and salary). Made several tries in the IF statement but none of them lead to what i needed.
class Workers {
public $name;
public $position;
public $salary;
private function Workers($name, $position, $salary){
$this->name = $name;
$this->position = $position;
$this->salary = $salary;
}
public function newWorker($name, $position, $salary){
// if ( ) {
return new Workers($name, $position, $salary);
// }
// else return NULL;
}
}
$arr = array();
$arr[] = Workers::newWorker("Peter", "work1", 600);
$arr[] = Workers::newWorker("John", "work2", 700);
$arr[] = Workers::newWorker("Hans", "work3", 550);
$arr[] = Workers::newWorker("Maria", "work4", 900);
$arr[] = Workers::newWorker("Jim", "work5", 1000);
print_r($arr);
This is my code and like that it will display all workers i have created but i need to output only the one with highest salary (worker 5 - Jim with 1000 salary)
You can use this snippet:
$max = null;
foreach ($arr as $worker) {
$max = $max === null ? $worker : ($worker->salary > $max->salary ? $worker : $max);
}
Or this, as more clarity:
$max = null;
foreach ($arr as $worker) {
if (!$max) {
$max = $worker;
} elseif ($worker->salary > $max->salary) {
$max = $worker;
}
}
$max now contains a worker with maximum salary.

Resources