AutoComplete foreach with 0 - php

I need to generate a row with some numbers like ", 0, 5, 21, 68, 2" (I will use them for some stats). Anyway, I get the numbers from a MySQL database and I process them with a foreach like this:
$stats= '';
foreach($rows as $row) {
$stats.= ', '.$row['total'];
}
The problem if that sometimes I don't have 5 rows, I have only 3 for example. What can I do to auto complete foreach with 0, 'till five numbers are generated, something like ", 0, 5, 21, 0, 0"? I have no ideea how to do that. Thank you!

You can simply loop through and add remaining zeros into array, and use implode with delimiter , to get desired result.
$stats = array();
foreach($rows as $row) {
$stats[] = $row['total'];
}
$count = count($stats);
for($i=$count; $i <= 5; $i++){
$stats[] = 0;
}
echo implode(',', $stats);

Related

How to find the sum of the values of this time series data set?

My controller is returning a time-series array for a graph, it also needs the total views count. The array it returns is in this format, need to calculate the sum of views corresponding ot the dates.
framework: Laravel
[
{
"2021-04-30": 0,
"2021-05-01": 0,
"2021-05-02": 0,
"2021-05-03": 0,
"2021-05-04": 0,
"2021-05-05": 0,
"2021-05-06": 1
}
]
$result = $as->getVisits();
$array = json_decode($result,1);
$total = 0;
foreach($array[0] as $date => $visits)
$total += 1;
echo $total;
return [$result, $total];
This look like a JSON array, you need first to decode it in a php array and then loop it to make the sum if you want to control over the dates
$array = json_decode($json,1);
$sumVisits = 0;
foreach($array[0] as $date => $visits)
$sumVisits += 1;
echo $sumVisits;
Or if you just want to sum everything you can use array_sum as pointed out in the comments by El_Vanja
$array = json_decode($json,1);
echo array_sum(array[0]);

why there is no output after running while loop in php?

When I run the code given below, it outputs nothing in the browser.
What Am I doing wrong? Please help.
$ages = [0, 4, 8, 12, 16, 20];
while($age = current($ages)){
echo $age.",";
next($ages);
}
To fix your current problem, when you use current($ages) in the first iteration of the loop, this will return the first item in the list - which is 0. As the while loop only continues whilst the value is not false (which 0 also counts) the loop will not be run, so...
while(($age = current($ages)) !== false){
echo $age.",";
next($ages);
}
alternatively, use a foreach loop...
foreach ( $ages as $age) {
echo $age.",";
}
The first test made is while (0), because the first value is 0. So, the loop is never executed.
You can use a foreach() loop instead
$ages = [0, 4, 8, 12, 16, 20];
foreach ($ages as $age) {
echo $age . ',';
}
Or just implode() for a better result (because it will not have a trailing ,).
echo implode(',', $ages);

How do I get a column in CSV in reverse order into php?

I would like to know how can I get a specific column (in my case the second column) from CSV in reverse order into PHP? For example if my file is
my, name, is, marwan
here, goes, thing, some
1, 2, 3, 4
Now the output the I want in php would be
my - some - 1
name - thing - 2
is - goes - 3
marwan - here - 4
My existing PHP code for printing everything in normal order is
for($num = 1; $num <= 1; $num++) {
if(file_exists('1.csv')) {
$csvData = file_get_contents('1.csv');
$lines = explode(PHP_EOL, $csvData);
$array = array();
foreach ($lines as $line) { $array[] = str_getcsv($line); }
// count number of columns and minus 1 from it
$count = count($array[0]) - 1;
for ($x = 0; $x <= $count; $x++) {
$first_column = $array[0][$x];
$second_column = $array[1][$x];
$third_column = $array[2][$x];
// Now just outputting the values...
";
}
}
}
Thank you.
Well, you can do it easily:
<?php
// defining a test array similar to yours
$records = array(
array(1, 'abc', '111'),
array(2, 'def', '222'),
array(3, 'ijk', '333'),
array(4, 'lmn', '444'),
array(5, 'opq', '555'),
);
// getting the column and reversing it
$col1rev = array_reverse(array_column($records, 1));
?>
You need to first make the CSV in to an array then reverse the second line.
Once that is done you foreach the first item in the array and use the key to output the other values.
$arr = explode("\n", $csv);
Foreach($arr as $key => &$line){
$line = explode(", ", $line);
If($key == 1) $line = array_reverse($line);
}
Unset($line);
Foreach($arr[0] as $key => $val){
Echo $val . "\t-\t" . $arr[1][$key] . "\t-\t" . $arr[2][$key] ."\n";
}
Output:
// The output here on SO looks odd but in reality it's tab separated
my - some - 1
name - thing - 2
is - goes - 3
marwan - here - 4
https://3v4l.org/MNLLF

Need Three Highest Values (or more, if tied) of PHP Array and Their Location?

I have an array. I'd like to get the three highest values of the array, but also remember which part of the array it was in.
For example, if my array is [12,3,7,19,24], my result should be values 24,19,12, at locations 4, 0, 3.
How do I do that? The first part is easy. Getting the locations is difficult.
Secondly, I'd like to also use the top three OR top number after three, if some are tied. So, for example, if I have [18,18,17,17,4], I'd like to display 18, 18, 17, and 17, at location 0,1,2,3.
Does that make sense? Is there an easy way to do that?
Wouldn't you be there using asort()?
For example:
<?php
$list = [4,18,18,17,17];
// Sort maintaining indexes.
asort($list);
// Slice the first 3 elements from the array.
$top3 = array_slice($list, -3, null, true);
// Results in: [ 1 => 18, 2 => 18, 3 => 17 ]
Or you can use arsort
function getMyTop($list, $offset, $top) {
arsort($list);
return array_slice($list, $offset, $top, true);
}
$myTop = getMyTop($list, 0, 3);
$myNextTop = getMyTop($list, 3, 4);
This is what you need!
<?php
$array = array(12,3,7,19,24);
$array_processed = array();
$highest_index = 0;
while($highest_index < 3)
{
$max = max($array);
$index = array_search($max,$array);
$array_processed[$index] = $max;
unset($array[$index]);
$highest_index++;
}
print_r($array_processed);
?>
You will get Index as well as the value! You just have to define how many top values you want! Let me know if it's what you want!
function top_three_positions($array){
// Sort the array from max to min
arsort($array);
// Unset everything in sorted array after the first three elements
$count = 0;
foreach($array as $key => $ar){
if($count > 2){
unset($array[$key]);
}
$count++;
}
// Return array with top 3 values with their indexes preserved.
return $array;
}
You can use a loop to determine how many elements your top-three-with-ties will have, after applying arsort:
function getTop($arr, $num = 3) {
arsort($arr);
foreach(array_values($arr) as $i => $v) {
if ($i >= $num && $v !== $prev) return array_slice($arr, 0, $i, true);
$prev = $v;
}
return $arr;
}
// Sample input
$arr = [4,18,17,6,17,18,9];
$top = getTop($arr, 3);
print_r($top); // [5 => 18, 1 => 18, 4 => 17, 2 => 17]
try this:
public function getTopSortedThree(array $data, $n = 3, $asc = true)
{
if ($asc) {
uasort($data, function ($a, $b) { return $a>$b;});
} else {
uasort($data, function ($a, $b) { return $a<$b;});
}
$count = 0;
$result = [];
foreach ($data as $key => $value) {
$result[] = $data[$key];
$count++;
if ($count >= $n){
break;
}
}
return $result;
}
Send false for desc order and nothing for asc order
Send $n with number of top values you want.
This functionality doesn't losing keys.
This task merely calls for a descending sort, retention of the top three values, and in the case of values after the third-positioned value being equal to the third value, retain these as well.
After calling rsort(), call a for() loop starting from the fourth element ([3]). If the current value is not equal to the value in the third position, stop iterating, and isolate the elements from the front of the array to the previous iteration's index. Done.
p.s. If the input array has 3 or fewer elements, the for() loop is never entered and the whole (short) array avoids truncation after being sorted.
Code: (Demo)
$array = [18, 17, 4, 18, 17, 16, 17];
rsort($array);
for ($i = 3, $count = count($array); $i < $count; ++$i) {
if ($array[2] != $array[$i]) {
$array = array_slice($array, 0, $i);
break;
}
}
var_export($array);
Because the loop purely finds the appropriate finishing point of the array ($i), this could also be compacted to: (Demo)
rsort($array);
for ($i = 3, $count = count($array); $i < $count && $array[2] === $array[$i]; ++$i);
var_export(array_slice($array, 0, $i));
Or slightly reduced further to: (Demo)
rsort($array);
for ($i = 3; isset($array[2], $array[$i]) && $array[2] === $array[$i]; ++$i);
var_export(array_slice($array, 0, $i));
Output:
array (
0 => 18,
1 => 18,
2 => 17,
3 => 17,
4 => 17,
)

Loop through Array and sum up values with same id

I have a total black out. I have one array with n elements which has the results of a team, such as:
array(teamid, wins, losses, draws, goals);
array(1, 2, 3, 4, 5);
array(2, 2, 3, 4, 5);
array(1, 1, 2, 2, 6);
array(2, 2, 3, 4, 5);
I want to iterate through this array and sum up the values for each team-id in a second array. Such as:
$results = getResults();
$final = array();
foreach ($results as $result) {
foreach ($results as $res) {
if ($res['team_id'] == $result['team_id']) {
...
}
}
}
foreach ($final as $finalresult) {
...print result
}
In the end I want an array with e.g. in this example 2 values with 2 different team ids, each values summed up, but I have a blackout at the moment.
Does anybody have a solution?
Thanks.
You're running the loops nested, which means you're actually summing n^2 records. Assuming the array keys are the same between both arrays, then you'd only need a single loop:
$arr1 = array(...);
$arr2 = array(...);
$sum = 0;
foreach($arr1 as $key => $value) {
$sum += $arr1[$key] + $arr2[$key];
}
If the keys aren't the same,t hen you'll have to figure out to match up the members of the two arrays.
Your code is confusing, but I guess it will give a hint:
$results = getResults();
$final = array();
foreach ($results as $result) {
if(!isset($final[$result['team_id']])) {
$final[$result['team_id']] = $result['wins'];
} else {
$final[$result['team_id']] += $result['wins'];
}
}
foreach($final as $key=>$value) {
echo $key . ' ' . $value . '</br>';
}

Categories