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]);
I want to get all prices and add them. I was planning on using this to loop through the JSON but that would be another question. Am I approaching this the wrong way? Is there a better way to get the SUM of all prices?
I have found this answer which makes the same question but it does not work (duplicate: PHP: How to access array element values using array-index). Here is my JSON string.
{
"data": {
"230723": {
"2019-11-15": {
"price": 52,
"min_length_of_stay": 2,
"available": 1
},
"2019-11-16": {
"price": 90,
"min_length_of_stay": 2,
"available": 0
},
"2019-11-17": {
"price": 44,
"min_length_of_stay": 2,
"available": 0
},
"2019-11-18": {
"price": 44,
"min_length_of_stay": 2,
"available": 0
}
}
}
}
And here is my code:
$resultJson = file_get_contents('http://....');
$priceRange = json_decode($resultJson, true);
echo $priceRange['data']['230723']['2019-11-15']['price']; // working
//$priceRange = array_values($priceRange);
echo $priceRange[0][0][0][0]; // not working
The first echo works and return 52. The second echo does not work with or without the commented line (which was the answer to the duplicate question).
What am I missing?
Instead of changing the array from associative to numeric just loop through already existing array
Like this
$sum = 0;
$resultJson = file_get_contents('http://....');
$priceRanges = json_decode($resultJson, true);
foreach ($priceRanges['data'] as $id => $priceRange) {
if (!is_array($priceRange)) {
continue;
}
foreach ($priceRange as $date => $priceInfo) {
$sum += (isset($priceInfo['price']) ? intval($priceInfo['price']) : 0);
}
}
Well you know I hope that the data is in data and if you don't know the next key then reset helps. Then just get all price keys (hopefully you know this as well) and sum them:
$result = array_sum(array_column(reset($array['data']), 'price'));
Another way is using array_values on the first two levels:
$result = array_sum(array_column(array_values(array_values($array)[0])[0], 'price'));
To get each price the way you were trying to do you would need:
$result = array_values(array_values(array_values(array_values($array)[0])[0])[0])[0];
The code I wrote using Krzysztof Janiszewski answer, and works.
$sum = 0;
$priceRange = json_decode($resultJson, true);
foreach($priceRange as $item) {
foreach($item as $item2){
foreach($item2 as $item3){
$sum += $item3['price'];
}
}
}
echo $sum;
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,
)
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);
I have a table that contain a sequence like this B05/FDH/CN/NM/00001, B05/FDH/CN/NM/00002
I need to get the max value from DB and add 1 to the sequence. the next number would be B05/FDH/CN/NM/00003
how do i do this
SQL and im getting max value as B05/FDH/CN/NM/00002
select MAX(`coverNoteNo`) as cnumber from covernotenonmotor where users_idusers = 8
Try this at Databse Level. this may help You in Code Optimization :)
select max(coverNoteNo), (SUBSTRING( max(coverNoteNo),0 , 15))+cast(cast((SUBSTRING( max(coverNoteNo),15 ,20)) as int)+1 as varchar) from covernotenonmotor
Save the result into a string then try this..
$string = 'B05/FDH/CN/NM/00002';
$stringpart = substr($string, 0, -5); // "B05/FDH/CN/NM/"
$numberpart = (integer) substr($string, -5); // "2"
$numberpart = $numberpart+1; // "3"
$numberpart = str_pad($numberpart, 5, "0", STR_PAD_LEFT); // "00003"
echo $result = $stringpart.$numberpart; // "B05/FDH/CN/NM/00003"
If you are fetching data as array from database you can also try this -
Assume you have fetched a array result set i.e. $arr than you can increment in a loop -
$arr = array('B05/FDH/CN/NM/00001', 'B05/FDH/CN/NM/00002'); //values from db
$b =array();
foreach($arr as $a)
{
$str = substr($a, 0, -5);
$b[] .= $str.str_pad(substr($a, -5) + 1, 5, "0", STR_PAD_LEFT);
}
print_r($b); //Array ( [0] = B05/FDH/CN/NM/00002 [1] = B05/FDH/CN/NM/00003 )