Create Associative Array inside a for loop - php

Hi I've created an array with a for loop inside. The array doesn't have any data inside it until it reaches the for loop. I wanted to add an associative array to what I've done so far. For example my array currently ouputs
[0] => Array
(
[0] => Version 5
[1] => Feb-16
[2] => gary
[3] => 80
[4] => P
)
I would like it to have headings instead of numbers
[0] => Array
(
Version => Version 5
Date => Feb-16
Name => gary
RandNum => 80
Letter => P
}
I'm not sure how i'd fit into my loop and how I could if my different columns these headings. Below is my current code. Which outputs the array at the top.
for($i = 0; $i <= 3; $i++){
for($j = 0; $j <= 4; $j++){
if ($j == 0){
$times_table[$i][$j]= "Version 5" ;
}
else if ($j == 1){
$cur_date = date("M-y", $currentdate);
$currentdate = strtotime('+1 month', $currentdate);
$times_table[$i][$j]= "<strong>" . $cur_date . "</strong>" ;
}
else{
$times_table[$i][$j]= "gary" ;
}
if ($j == 3) {
$numbers = mt_rand(1, 100);
$times_table[$i][$j]= $numbers ;
}
if ($j == 4){
if($i == 0 || $i == 3)
{
$pay = "P";
$times_table[$i][$j]= $pay ;
}
else{
$int = "I";
$times_table[$i][$j]= $int ;
}
}
}
}

Try this..
for($i = 0; $i <= 3; $i++){
for($j = 0; $j <= 4; $j++){
if ($j == 0){
$times_table[$i]['Version']= "Version 5" ;
}
else if ($j == 1){
$cur_date = date("M-y", $currentdate);
$currentdate = strtotime('+1 month', $currentdate);
$times_table[$i]['Date']= "<strong>" . $cur_date . "</strong>" ;
}
else{
$times_table[$i]['Name']= "gary" ;
}
if ($j == 3) {
$numbers = mt_rand(1, 100);
$times_table[$i]['RandNum']= $numbers ;
}
if ($j == 4){
if($i == 0 || $i == 3)
{
$pay = "P";
$times_table[$i]['Letter']= $pay ;
}
else{
$int = "I";
$times_table[$i]['Letter']= $int ;
}
}
}
}
Hope this will solve your problem.

In my opinion, your second for loop is not needed. You should know that you can create associative arrays like this :
<?php
$times_table = [];
$times_tables[] = [
'Version' => 'Version 5',
'Date' => 'Feb-16',
'Name' => 'gary',
'RandNum' => '80',
'Letter' => 'P',
];
To match with your code :
<?php
$times_table = [];
for($i = 0; $i <= 3; $i++){
$times_table[$i]['Version']= "Version 5" ;
$cur_date = date("M-y", $currentdate);
$currentdate = strtotime('+1 month', $currentdate);
$times_table[$i]['Date']= "<strong>" . $cur_date . "</strong>" ;
$times_table[$i]['Name']= "gary" ;
$numbers = mt_rand(1, 100);
$times_table[$i]['RandNum']= $numbers ;
switch ($i) {
case 0:
case 3:
$letter = 'P';
break;
default:
$letter = 'I';
}
$times_table[$i]['Letter']= $letter;
}
I think this should do what you want in a cleaner way !

for($i = 0; $i <= 3; $i++){
for($j = 0; $j <= 4; $j++){
if ($j == 0){
$times_table["Version"][$j]= "Version 5" ;
}
else if ($j == 1){
$cur_date = date("M-y", $currentdate);
$currentdate = strtotime('+1 month', $currentdate);
$times_table["Date"][$j]= "<strong>" . $cur_date . "</strong>" ;
}
else{
$times_table["Name"][$j]= "gary" ;
}
if ($j == 3) {
$numbers = mt_rand(1, 100);
$times_table["RandNum"][$j]= $numbers ;
}
if ($j == 4){
if($i == 0 || $i == 3)
{
$pay = "P";
$times_table["Letter"][$j]= $pay ;
}
else{
$int = "I";
$times_table["Letter"][$j]= $int ;
}
}
}
}

You can create associative array like this:
$a=array("Version"=> "Version 5",
"Date"=> "Feb-16",
"Name" => "gary",
"RandNum" => 80,
"Letter" => "P"
)
To access this array in for loop use $a['key']. For eg. to access version5, use $a['version'], to access Feb-16 use $a['Date'].

Related

How to show the next interest rate like image expected below

Expectation
My Code
<?php
$value = 100;
$years = 5;
for ($i = 1; $i <= $years; $i++) {
$income = round($value * (pow(1+6/100, $i)), 2);
echo $i, " ", $income, "<br>";
}
?>
Output
1 106
2 112.36
3 119.1
4 126.25
5 133.82
How can I get result like my expectation above ?
Just add one more loop
$value = 100;
$years = 5;
for ($i = 1; $i <= $years; $i++) {
$income = array();
for ($j = 6; $j <= 10; $j++) {
$income[] = round($value * (pow(1+$j/100, $i)), 2);
}
echo $i, " ", implode(' ', $income), "<br>";
}

PHP Calendar days left only of current month

I'm using an calendar rendering library (simplecalender/donatj) for one of my projects but I can't figure out how to display only the days left of current month and not the full month.
As far as I understand, this is the part that builds the calender:
public function show( $echo = true ) {
if( $this->wday_names ) {
$wdays = $this->wday_names;
} else {
$today = (86400 * (date("N")));
$wdays = array();
for( $i = 0; $i < 7; $i++ ) {
$wdays[] = strftime('%a', time() - $today + ($i * 86400));
}
}
$this->arrayRotate($wdays, $this->offset);
$wday = date('N', mktime(0, 0, 1, $this->now['mon'], 1, $this->now['year'])) - $this->offset;
$no_days = cal_days_in_month(CAL_GREGORIAN, $this->now['mon'], $this->now['year']);
If I change no_days to 25 only days 1-25 are displayed within the calendar. So almost what I want.
Any idea how I can display 25 to 31 only (days left for July)?
Thanks.
Here's the rest of the code:
$out = '<table cellpadding="0" cellspacing="0" class="SimpleCalendar"><thead><tr>';
for( $i = 0; $i < 7; $i++ ) {
$out .= '<th>' . $wdays[$i] . '</th>';
}
$out .= "</tr></thead>\n<tbody>\n<tr>";
$wday = ($wday + 7) % 7;
if( $wday == 7 ) {
$wday = 0;
} else {
$out .= str_repeat('<td class="SCprefix"> </td>', $wday);
}
$count = $wday + 1;
for( $i = 1; $i <= $no_days; $i++ ) {
$out .= '<td' . ($i == $this->now['mday'] && $this->now['mon'] == date('n') && $this->now['year'] == date('Y') ? ' class="today"' : '') . '>';
$datetime = mktime(0, 0, 1, $this->now['mon'], $i, $this->now['year']);
$out .= '<time datetime="' . date('Y-m-d', $datetime) . '">' . $i . '</time>';
$dHtml_arr = false;
if( isset($this->dailyHtml[$this->now['year']][$this->now['mon']][$i]) ) {
$dHtml_arr = $this->dailyHtml[$this->now['year']][$this->now['mon']][$i];
}
if( is_array($dHtml_arr) ) {
foreach( $dHtml_arr as $dHtml ) {
$out .= '<div class="event">' . $dHtml . '</div>';
}
}
$out .= "</td>";
if( $count > 6 ) {
$out .= "</tr>\n" . ($i != $count ? '<tr>' : '');
$count = 0;
}
$count++;
}
$out .= ($count != 1 ? str_repeat('<td class="SCsuffix"> </td>', 8 - $count) : '') . "</tr>\n</tbody></table>\n";
if( $echo ) {
echo $out;
}
return $out;
}
private function arrayRotate( &$data, $steps ) {
$count = count($data);
if( $steps < 0 ) {
$steps = $count + $steps;
}
$steps = $steps % $count;
for( $i = 0; $i < $steps; $i++ ) {
array_push($data, array_shift($data));
}
}

Get all possible substring in php

I am trying to get a list of all substring of input.
for input=a, substrings {'','a'}
for input=ab, substrings {'','a','b','ab','ba'}
for input=abc, substrings {'','a','b','c','ab','bc','ca','ba','cb','ac','abc','acb','bac','bca','cab','cba'}
and so on.
The code I tried is here
function get_substr($string){
$array=str_split($string);
static $k=0;
for ($i=0; $i <count($array) ; $i++) {
for ($j=0; $j <count($array) ; $j++) {
$new_array[$k]=substr($string, $i, $j - $i + 1);
$k++;
}
}
return($new_array);
}
and i have o/p of this code as below
Please suggest me what changes I need or any alternative idea to do this work.
function find_posible_substr($input){
$input_len = strlen($input);
$possubstr = array();
$i = 0;
while($i < $input_len){
$j = 0;
while($j < $input_len){
$possubstr[] = substr($input, $j, $i + 1);
if(substr($input, $j, $i + 1) == $input){
break;
}
$j++;
}
$i++;
}
return $possubstr;
}
I don't know if you are still on this problem. But I want to share mine anyway.
If the input is abc then the output will be as below.
Array
(
[0] => a
[1] => b
[2] => c
[3] => ab
[4] => bc
[5] => c
[6] => abc
)
<?php
// function to generate and print all N! permutations of $str. (N = strlen($str)).
function permute($str,$i = null,$n = null) {
if(is_null($n)) $n = mb_strlen($str);
if(is_null($i)) $i = 0;
if ($i == $n)
print "$str \n";
else {
for ($j = $i; $j < $n; $j++) {
swap($str,$i,$j);
permute($str, $i+1, $n);
swap($str,$i,$j); // backtrack.
}
}
}
// function to swap the char at pos $i and $j of $str.
function swap(&$str,$i,$j) {
$temp = $str[$i];
$str[$i] = $str[$j];
$str[$j] = $temp;
}
$str = "hey";
permute($str); // call the function.
see this SO answer
$str = "abcd";
$str_arr = str_split($str);
for($i = 0; $i <= count($str_arr)-1 ;$i++){
for($j = $i+1 ; $j <= count($str_arr) ; $j++){
for($k = $i; $k <= $j-1; $k++){
$subsrt1.= $str_arr[$k];
}
$substr[] = $subsrt1;
$subsrt1 = '';
}
}
print_r($substr);

print number vertically and grouping it

I am trying to print number vertically and it must be in group
here is my code
$nums = 105;
$rows = 8;
$col = floor($nums / $rows);
$group = floor($col / 3);
$count = 0;
for ($g = 0; $g <= $group; $g++) {
echo "<div class='group'>";
for ($i = 1; $i <= $rows; $i++) {
for ($j = $i; $j <= 24; $j = $j + $rows) {
$count++;
if($count>$nums){
break;
}
echo "<div class='fleft'>$count</div>";
}
echo "<div class='clear'></div>";
}
echo "</div>";
}
out of above
but i want output like for the first column
and next group number will start from where first group number end. in this case next group start from 25
please ask if any doubt
$nums = 105;
$rows = 8;
$colsize = 3;
$col = floor($nums / $rows);
$group = floor($col / $colsize);
$count = 0;
$groupsize = $rows * $colsize;
for ($g = 0; $g <= $group; $g++) {
echo "<div class='group'>";
$modulo = 0;
$correction = 0;
$rest = $nums - $count;
if ($rest < $groupsize) {
$empty = $groupsize - $rest;
$correction = floor($empty / $colsize);
$modulo = $empty % $colsize;
}
for ($i = 1; $i <= $rows; $i++) {
$colind = 0;
for ($j = $i; $j <= $groupsize; $j = $j + $rows) {
$count++;
if ($count > $nums) {
break;
}
$val = $j + ($g * $groupsize);
$val -= $colind * $correction;
$modcor = $colind - ($colsize - $modulo);
if ( $modcor > 0 ) {
$val -= $modcor;
}
echo "<div class='fleft'>" . $val . "</div>";
$colind++;
}
echo "<div class='clear'></div>";
}
echo "</div>";
}
This works:
Also, you can change number of digits, columns or size of column
for($group = 0; $group < 3; $group++){
for($row =1 ; $row <= 8; $row++){
for($col = 0; $col <= 2; $col++){
echo ($group*24)+ $row + 8 * $col; echo " ";
}
echo "\n";
}
}
This code will print the number in the requested format. You need to modify according to your need.
may be i am mad , made a simple alter .... try this
$nums = 105;
$rows = 8;
$col = floor($nums / $rows);
$group = floor($col / 3);
$count = 0;
$letCounter=0; //added a counter
for ($g = 0; $g <= $group; $g++) {
echo "<div class='group'>";
for ($i = 1; $i <= $rows; $i++) {
$letCounter=0; //reset counter on each loop
for ($j = $i; $j <= 24; $j = $j + $rows)
{
$count++;
if($count>$nums)
{break;}
//made an alter in the below line , some math :)
echo "<div class='fleft'>".($letCounter++ * $rows +$i)."</div>";
}
echo "<div class='clear'></div>";
}
echo "</div>";
}
Thanks !
This May work
$nums = 105;
$rows = 8;
$col = floor($nums / $rows);
$group = floor($col / 3);
$count = 0;
$flag = true;
for($c=1;$c<=$col;$c++)
{
if($c%$group== 1)
{
echo "Group Start";
$flag = false;
}
for ($i = 1; $i <= $rows; $i++) {
$count++;
echo "<div class='fleft'>$count</div>";
echo "<div class='clear'></div>";
}
echo "Line End";
if($c%$group == 2&& $flag)// Check here for your requirement
echo "Group End </br>";
$flag = true;
}

PHP combine rows

I am working on a PHP project in which I need to combine rows (the rule is: if the first two numbers matched then add the rest numbers)
I have this array :
array_b4_combine= [
[2,15,1,1,0],
[2,15,3,3,0],
[2,15,1,1,0],
[2,21,2,2,0],
[2,24,7,7,0],
[2,24,2,2,0],
[3,15,1,1,0],
[3,15,7,7,0],
[3,24,1,1,0]];
the output should be :
combined= [
[2,15,5,5,0],
[2,21,2,2,0],
[2,24,9,9,0],
[3,15,8,8,0],
[3,24,1,1,0]];
This is my code :
$num1 = $array_b4_combine[0][0];
$num2 = $array_b4_combine[0][1];
$sum1 = 0;
$sum2 = 0 ;
$sum3 = 0 ;
$combined ;
for ( $i = 0 ; $i < count($array_b4_combine) ; $i++)
{
if ($num1 == $array_b4_combine[$i+1][0] && $num2 == $array_b4_combine[$i+1][1])
{
$sum1 = $sum1 + $array_b4_combine[$i][2];
$sum2 = $sum2 + $array_b4_combine[$i][3];
$sum3 = $sum3 + $array_b4_combine[$i][4];
}
else
{
$combined[] = array($num1 , $num2 , $sum1, $sum2, $sum3);
$day = $array_b4_combine[$i][0];
$time = $array_b4_combine[$i][1];
$sum1 = $array_b4_combine[$i][2];
$sum2 = $array_b4_combine[$i][3];
$sum3 = $array_b4_combine[$i][4];
}
}
the output for my code is this:
combined=
[[2,15,4,4,0],
[2,15,1,1,0],
[2,21,2,2,0],
[2,24,7,7,0],
[2,24,2,2,0],
[3,15,1,1,0],
[3,15,7,7,0]];
Am I doing the reset clause in wrong order.. can someone figure out what is the problem here.
Thanks
I really cannot understand your code, try this one:
$combined = [];
foreach ($array_b4_combine as $i => $arrayRow) {
$k = $arrayRow[0].' '.$arrayRow[1];
if (isset($combined[$k]))
for ($i=2; $i<5; $i++)
$combined[$k][$i] += $arrayRow[$i];
else
$combined[$k] = $arrayRow;
}
$combined = array_values($combined);
Here is how i solved your problem . code can be optimized .
<?php
$array_b4_combine = [
[2,15,1,1,0],
[2,15,3,3,0],
[2,15,1,1,0],
[2,21,2,2,0],
[2,24,7,7,0],
[2,24,2,2,0],
[3,15,1,1,0],
[3,15,7,7,0],
[3,24,1,1,0]];
$j =0;
for ( $i = 0 ; $i < count($array_b4_combine) -1 ; $i++)
{
if($i == 0)
{
$sum1 = $array_b4_combine[$i][2];
$sum2 = $array_b4_combine[$i][3];
$sum3 = $array_b4_combine[$i][4];
}
if(($array_b4_combine[$i][0] == $array_b4_combine[$i+1][0]) && ($array_b4_combine[$i][1] == $array_b4_combine[$i+1][1]) )
{
$sum1 = $sum1 + $array_b4_combine[$i+1][2];
$sum2 = $sum2 + $array_b4_combine[$i+1][3];
$sum3 = $sum3 + $array_b4_combine[$i+1][4];
$combined[$j][0] = $array_b4_combine[$i][0];
$combined[$j][1] = $array_b4_combine[$i][1];
$combined[$j][2] = $sum1;
$combined[$j][3] = $sum2;
$combined[$j][4] = $sum3;
}
else
{ $j++;
$combined[$j][0] = $array_b4_combine[$i+1][0];
$combined[$j][1] = $array_b4_combine[$i+1][1];
$combined[$j][2] = $array_b4_combine[$i+1][2];
$combined[$j][3] = $array_b4_combine[$i+1][3];
$combined[$j][4] = $array_b4_combine[$i+1][4];
$sum1 = $combined[$j][2];
$sum2 = $combined[$j][3];
$sum3 = $combined[$j][4];
}
}
echo "<pre>";
print_r($combined);
echo "</pre>";
?>

Categories