Increase year after every 3 iterations while looping - php

I have an array contain n number of elements can be 6 or 8, like that:
$langs = ["PHP", "JAVA", "Ruby", "C", "C++", "Perl"];
I would like to add one year evenly next to the elements
Desired output in case of 6 elements:
PHP - 2022
JAVA - 2022
Ruby - 2022
C - 2023
C++ - 2023
Perl - 2023
Desired output in case of 9 elements:
PHP - 2022
JAVA - 2022
Ruby - 2022
C - 2023
C++ - 2023
Perl - 2023
Python - 2024
Javascript - 2024
Mysql - 2024
My try :
$date = Carbon::now();
foreach($langs as $key => $lang){
if(count($langs) % $key == 0){
echo $lang .' - '. $date->addYear();
}
}

Bump the year every time $key is not zero and $key / 3 has no remainder.
Code: (Demo)
$langs = ["PHP", "JAVA", "Ruby", "C", "C++", "Perl", "Perl", "Python", "Javascript", "Mysql"];
$date = Carbon::now();
foreach ($langs as $key => $lang){
if ($key && $key % 3 === 0) {
$date->addYear();
}
echo $lang .' - '. $date->year . PHP_EOL;
}
To be perfectly honest, I don't see any benefit is calling a datetime wrapper for this very basic task. You can easily replace all usage of Carbon with PHP's native date() function. (Demo)
$langs = ["PHP", "JAVA", "Ruby", "C", "C++", "Perl", "Perl", "Python", "Javascript", "Mysql"];
$year = date('Y');
foreach ($langs as $key => $lang){
if ($key && $key % 3 === 0) {
++$year;
}
echo $lang .' - '. $year . PHP_EOL;
}

I'd use %3 as suggested by #mickmackusa but I would avoid incrementing the year of a date object as here you just need to get the year number and increment it (the month/day/hour/etc. is not an info you need to keep):
$langs = ["PHP", "JAVA", "Ruby", "C", "C++", "Perl", 'foo', 'bar', 'bam'];
$year = Carbon::now()->year;
foreach ($langs as $key => $lang){
if ($key && $key % 3 === 0) {
$year++;
}
echo $lang .' - '. $year . PHP_EOL;
}

Related

find the biggest value in associative arrays php

I would like to find the biggest sum in associative array. I have information for 2 years and i have found the sum for each year and now I want to find which one is bigger and which year this sum belongs to.
<?php
$year = array (
"Year 2015 " => array(
"Televizor " => "3",
"Lavatrice" => "4",
"Kompjuter" => "5",
"printer" => "5",
),
"Year 2016 " => array(
"Televizor " => "3",
"lavatrice" => "7",
"kompjuter" => "4",
"printer" => "1",
)
);
foreach($year as $key => $product){
echo "<br>";
echo "$key";
echo"<table border=1 cellspacing=0>
<tr>
<td>Produkti</td>
<td>Sasia</td>
</tr>";
echo "<br>";
foreach( $product as $key => $value){
echo "<tr>
<td>$key</td>
<td>$value</td>
</tr>";
}
echo "</table>";
}
foreach($year as $key => $product){
echo"$key";
$arrayOfValues=array_values($product);
$arraySum=array_sum($arrayOfValues);
$avg=$arraySum/count($arrayOfValues);
echo "Average=$avg";
echo " ";
$maxValueArray=array();
array_push($maxValueArray, $arraySum);
echo "Sum=$maxValueArray[0]";
echo "<br>";
}
?>
and this is the output :
Year 2015
Produkti Sasia
Televizor 3
Lavatrice 4
Kompjuter 5
printer 5
Year 2016
Produkti Sasia
Televizor 3
lavatrice 7
kompjuter 4
printer 1
Year 2015 Average=4.25 Sum=17
year 2016 Average=3.75 Sum=15
i would like to print "Year 2015 has the biggest sum =17 "
To do it, you just need to create an array with the valuation.
$yearSumValues = array_map('array_sum', $year);
$max = max($yearSumValues);
$maxYearKey = array_search($max, $yearSumValues);
echo 'Max sum is: ', $max, '<br />';
echo 'Data key is: ', $maxYearKey, '<br />';
if( !is_null($maxYearKey) ) {
echo 'Values are: ', var_dump($year[$maxYearKey]);
}
So, now, in $max you will have the biggest value. So, $maxYearKey contains the key of the biggest year (be careful with equalities).
var_dump($year[$maxYearKey]);
Produkti Sasia
Televizor 3
Lavatrice 4
Kompjuter 5
printer 5
Compact version
$yearSumValues = array_map('array_sum', $year);
if( ($maxYearKey = array_search(max($yearSumValues), $yearSumValues)) != null ) {
echo 'found ', $maxYearKey, ' with values ', var_dump($year[$maxYearKey]);
}
You can play: http://phplab.io/lab/IgJkR
Short solution using array_reduce, array_sum and array_search functions:
$result = array_reduce($year, function ($prev, $item) {
return (array_sum($prev) > array_sum($item))? $prev : $item;
}, []);
print_r(array_search($result, $year) ." has the biggest sum = ". array_sum($result));
The output:
Year 2015 has the biggest sum = 17
http://php.net/manual/en/function.array-reduce.php

How to change the time in .php

I want to convert the time when i echo from database to .php page.
When i upload a csv to database the table row with duration looks like this:
TABLE ROW:
|Duration|
500 > 5:00
234 > 2:34
1100 > 11:00
520 > 5:20
1300 > 13:00
10000 > 1:00:00
So what i want is to show it like this > 5:00.
If i change the TABLE ROW Duration in to TIME than i get this 00:05:00.
So what do i need to change it like above explained ?
Hopefully I explained it well
Thanks in advance.
<?php
foreach (array(500, 234, 1100, 520, 1300, 10000) as $number) {
echo $number, "\t";
$number = str_pad($number, 6, 0, STR_PAD_LEFT);
echo ltrim($number{0}.$number{1}.':'.$number{2}.$number{3}.':'.$number{4}.$number{5}, ":0"), "\n";
}
http://codepad.org/FrjWtgqx
Function wordwrap() could be useful:
foreach (['500', '234', '1100', '520', '1300', '10000'] as $number) {
$time = strrev($number);
$time = wordwrap($time, 2, ':', true);
$time = strrev($time);
echo "$number was transformed to $time\n";
}
demo

PHP foreach on nested array

I am doing a GET php function on a URL and I get back the resulting response in JSON:
{
"results": [{
"text": "The 2014 BICSI Canadian Conference and Exhibition in Vancouver, British Columbia, Canada is 61 days away on April 27 - 30.",
"createdAt": "2014-02- 24T19:54:08.707Z",
"updatedAt": "2014-02-24T19:54:08.707Z",
"objectId": "ZZrZ9OgyRG"
}, {
"text": "Only 33 more days fro the 2014 BICSI Canadian Conference and Exhibition in Vancouver, Canada!",
"createdAt": "2014-03-24T13:23:56.240Z",
"updatedAt": "2014-03-24T13:23:56.240Z",
"objectId": "ZqxJRiHoJo"
}]
}
I am able to do php json_decode and display the results below on a web page like below
text | The 2014 BICSI Canadian Conference and Exhibition in Vancouver, British Columbia, Canada is 61 days away on April 27 - 30.
createdAt | 2014-02-24T19:54:08.707Z
updatedAt | 2014-02-24T19:54:08.707Z
objectId | ZZrZ9OgyRG
text | Only 33 more days fro the 2014 BICSI Canadian Conference and Exhibition in Vancouver, Canada!
createdAt | 2014-03-24T13:23:56.240Z
updatedAt | 2014-03-24T13:23:56.240Z
objectId | ZqxJRiHoJo
The php code I used to display the results above on the web page is:
$returned_content = get_data('https://api.parse.com/1/classes/Alerts');
$data = json_decode($returned_content, true);
foreach ($data as $array1 => $arrayn) {
foreach ($arrayn as $k => $v) {
foreach ($v as $t => $s) {
echo"<p> $t | $s ";
}
}
}
If I just wanted to display the 'text' key/value info only on the web page, how should I modify the php. Meaning all I want to see displayed on the web page is:
text | The 2014 BICSI Canadian Conference and Exhibition in Vancouver, British Columbia, Canada is 61 days away on April 27 – 30.
text | Only 33 more days fro the 2014 BICSI Canadian Conference and Exhibition in Vancouver, Canada!
$data = json_decode($json);
foreach ($data->results as $item) {
echo '<br>text | '.$item->text;
}
If you don't add the second json_decode() paremeter, you can just use your JSON with the StdClass.
Wrap it inside a simple if condition.
foreach ($data as $array1 => $arrayn) {
foreach($arrayn as $k => $v) {
foreach ($v as $t => $s) {
if($t == 'text') {
echo"<p> $t | $s ";
}
}
}
}
do like this
$returned_content = get_data('https://api.parse.com/1/classes/Alerts');
$data = json_decode($returned_content, true);
foreach ($data as $array1 => $arrayn) {
foreach($arrayn as $k => $v){
foreach ($v as $t => $s)
{
if($t == "text")
echo"<p> $t | $s ";
}
}
}
After this line :
$data = json_decode($returned_content, true);
You have an associative array, so you can change your loop to :
foreach ($data as $array1 => $arrayn) {
foreach($arrayn as $k => $v) {
foreach ($v as $t => $s) {
if('text' === $t) {
echo"<p> $t | $s ";
}
}
}
}
Make it simple and with a check if the key exists, just in case the JSON does not contain the key "text" it will return notice.
$data = json_decode($str,true);
foreach($data["results"] as $key=>$val){
if(array_key_exists("text",$val)){
echo 'text | '.$val["text"];
echo '<br />';
}
}
Here $str is your json string.

How do i split a string from a csv file to a partiqular format in php?

I have a csv file with the folowing lines(2 for example):
004000001001030212001Y 5372 #0001 N,"1","2","3","4","5","5","0"
004000002001030212001Y 5372 #0001 N,"1","2","3","4","5","5","0"
What I want to do is to read the csv file in php and then reformat it in the following way:
id date lp Lang token cod1 cod2 cod3 cod4 cod5 cod6 cod7
1 03/02/2012 18:00 2 el grapto 1 2 3 4 5 5 0
2 03/02/2012 18:00 2 el grapto 1 2 3 4 5 5 0
The id is the 8 and 9th digit. Date is the 13th until 18th digit. And then export it to csv again.
Any help will do.
Thanks
There's fgetcsv for stuff like this
http://sg2.php.net/manual/en/function.fgetcsv.php
to get id and date from that long string you could do:
$id = substr($longString, 8, 2);
$dateStr = substr($longString, 13, 8);
$date = substr($dateStr, 0, 2) . '/' . substr($dateStr, 2, 2) . '/' . substr($dateStr, 4, 4);
Now go and implement :)
Not sure how you get 18:00 2 el grapto from those inputs, but this will do the other stuff:
$lines = explode("\n", $file);
echo "id date Ip Lang token cod1 cod2 cod3 cod4 cod5 cod6 cod7\n";
foreach ($lines as $line)
{
$values = explode(",", $line);
$string = array_shift($values);
$values = array_map(function($value) { return str_replace("\"", "", $value); }, $values);
$id = substr($string, 7, 2);
$date = date_parse_from_format("mdy", substr($string, 12, 6));
$date = date("m/d/Y", mktime(0, 0, 0, $date["month"], $date["day"], $date["year"]));
list(, $ip, $lang, $token) = explode(" ", $string);
array_unshift($values, $id, $date, $ip, $lang, $token);
echo implode(" ", $values) ."\n";
}
Outputs:
id date Ip Lang token cod1 cod2 cod3 cod4 cod5 cod6 cod7
01 03/02/2012 5372 #0001 N 1 2 3 4 5 5 0
02 03/02/2012 5372 #0001 N 1 2 3 4 5 5 0

Add characters to month loop?

I currently have a php loop running exactly how I need it with proper validations (in both php and javascript) with one exception, if the month is less than 2 digits, (i.e. 1,2,3,4), I need for a '0' to appear before:
01 - January
02 - February
...
10 - October
My code for the loop is currently:
<select name="Month">
<option value="">Month</option>
<?php
for ($i=1; $i<=12; $i++)
{
echo "<option value='$i'";
if ($fields["Month"] == $i)
echo " selected";
echo ">$i</option>";
}
?>
</select>
Also note, this month date is being stored in session, not interested in printing to screen
Try this when outputting the month:
sprintf("%02d", $month); // 01, 02 .. 09, 10, 11...
Use sprintf($format, [$var, [$var...).
Here, have some code:
function padLeft($char, $s, $n) {
return sprintf("%" . $char . $n . "d", $s);
}
function padWithZeros($s, $max_length) {
return padLeft('0', $s, $max_length);
}

Categories