Simple PHP Array - How do I get the results to a variable? - php

I'm trying to get the results of an array and move them to a $variable.
This is my current code:
<?php
$total_days_month = date('t'); // total days this month
// add "$currentday" day number to an array until $currentday<=$total_days_month
$days_array = array();
for ($currentday=1; $currentday<=$total_days_month; $currentday++) {
if ($total_days_month > $currentday)
{
array_push($days_array,"'$currentday',");
}
else
{
array_push($days_array,"'$currentday'");
}
}
// now transfer the array content to a $variable
$variable = ????
?>
$variable content must be '1', '2', '3', '4' ........ '31'

$variable = implode("','", $days_array);

<?php
$total_days_month = date('t'); // total days this month
// add "$currentday" day number to an array until $currentday<=$total_days_month
$days_array = array();
for ($currentday=1; $currentday<=$total_days_month; $currentday++) {
if ($total_days_month > $currentday){
array_push($days_array,"'$currentday',");
}else{
array_push($days_array,"'$currentday',");
}
}
// now transfer the array content to a $variable
$variable = implode(',', $days_array);

Related

PHP - get closest date from array

I want to get closest date from $search_date if is not same values in $array['date']. If is same value in $array['date'] I want all array.
Format date is 'Y-m-d'.
Example 1:
$search_date = '2022-12-08';
$array = [{"price":"200","date":"2022-12-12"},{"price":"50","date":"2022-12-10"},{"price":"100","date":"2022-12-10"}]
Return should be: [{"price":"50","date":"2022-12-10"},{"price":"100","date":"2022-12-10"}]
Example 2:
$search_date = '2022-12-08';
$array = [{"price":"200","date":"2022-12-08"},{"price":"50","date":"2022-12-09"},{"price":"100","date":"2022-12-11"}]
Return should be: [{"price":"200","date":"2022-12-08"}]
Example 3:
$search_date = '2022-12-08';
$array = [{"price":"200","date":"2022-12-10"},{"price":"100","date":"2022-12-10"},{"price":"50","date":"2022-12-11"}]
Return should be: [{"price":"200","date":"2022-12-10"},{"price":"100","date":"2022-12-10"}]
Example 4:
$search_date = '2022-12-08';
$array = [{"price":"200","date":"2022-12-08"},{"price":"100","date":"2022-12-08"},{"price":"50","date":"2022-12-08"}]
Return should be: [{"price":"200","date":"2022-12-08"},{"price":"100","date":"2022-12-08"},{"price":"50","date":"2022-12-08"}]
Thank you!
This code calculates the distance in days between $search and each record. It assumes that you want to find closest distance in both future and past.
<?php
/*
Question Author: Catalin Iamandei
Question Answerer: Jacob Mulquin
Question: PHP - get closest date from array
URL: https://stackoverflow.com/questions/74598442/php-get-closest-date-from-array
Tags: php, arrays, laravel, date, php-carbon
*/
$search = '2022-12-10';
$searchObj = new DateTime($search);
$records = json_decode('[{"price":"200","date":"2022-12-10"},{"price":"100","date":"2022-12-10"},{"price":"50","date":"2022-12-11"}]', true);
$distances = [];
foreach ($records as $index => $record) {
$recordObj = new DateTime($record['date']);
$daysDiff = $searchObj->diff($recordObj)->format("%r%a");
$distances[$index] = abs($daysDiff);
}
$minimumDiff = min($distances);
$output = [];
foreach ($distances as $index => $distance) {
if ($distance == $minimumDiff) {
$output[] = $records[$index];
}
}
echo json_encode($output, JSON_PRETTY_PRINT);
Yields:
[
{
"price": "50",
"date": "2022-12-09"
},
{
"price": "100",
"date": "2022-12-11"
}
]
If you only want to search for closest dates in the future, you need to remove the abs() function and then remove all negative entries in the $distances array before using min().
If you want to search for a specific value in your array have you tried
array_search($value, $array);
By this you can search for a specific value in your array
If you want to search the lowest value
try to for looping your array and check if the array is lower than the previous index and if the for loop has ended you have the lowest date
$lowest_date = null;
for ($i = 0; count($i); $i++) {
if ($array['date'] < $lowest_date) {
$lowest_date = $array['date'];
}
}
you dont have mentioned what todo with prior dates, eg. searching for '2022-12-07', how to tread 2022-12-06 and 2022-12-08, as the difference both is 1. You can calculate the datediff for each entry, get the min datediff and output elements with this datediff. eg :
<?php
$SearchDate = new DateTimeImmutable('2022-12-08');
$array = array ('{"price":"200","date":"2022-12-12"}',
'{"price":"50","date":"2022-12-10"}',
'{"price":"100","date":"2022-12-10"}');
$laResult = array();
foreach($array as $jsonO) {
$json = json_decode($jsonO);
$CompareDate = new DateTimeImmutable($json->{'date'});
$interval = date_diff($SearchDate, $CompareDate);
$laThis['date'] = $json->{'date'};
$laThis['diff'] = $interval->format('%a');
$laThis['origin'] = $jsonO;
$laResult[] = $laThis;
}
$min_diff = min( array_column( $laResult, 'diff') );
echo 'nearestDiff:'. $min_diff .PHP_EOL;
foreach($laResult as $laSingleResult) {
if($laSingleResult['diff'] == $min_diff) {
echo $laSingleResult['origin'] .PHP_EOL;
}
}

how to sort an array in descending order in php

Newly-entered products are displayed in the last row. If there is a large amount, it is difficult to see at the bottom. How can I change the new display to the top. Thank you!
$barcodes_ary = explode(',', $barcodes);
$barcodes_hash = array ();
foreach ($barcodes_ary as $b) {
if (array_key_exists($b, $barcodes_hash)) {
$barcodes_hash[$b] += 1;
} else {
$barcodes_hash[$b] = 1;
}
}
foreach ($barcodes_hash as $b => $amount) {
if ($barcodes_ary == array(''))continue;
$ary = get_sql("SELECT * FROM Products WHERE Barcode='$b' Order by ProductName");
if ( count($ary) == 0 ) {
continue;
}
$pid = $ary[0]['ProductID'];
$pn = $ary[0]['ProductName'];
$unit = $ary[0]['UnitID'];
$ary2 = get_sql("SELECT UnitName FROM Units WHERE UnitID = '$unit'");
$unit = $ary2[0]['UnitName'];
?>
<TR>
<TD><? echo "$pn"; ?></TD>
<TD>
<INPUT TYPE=hidden NAME=productid<?=$pid?> VALUE='<?=$pid?>'>
<?
$candidates = array();
for($i=1; $i <= DropDownMaxValue; $i++) {
$candidates[]=$i;
}
//update
I use another way to solve the problem. Just display the same product.
function push_barcode() {
// alert('barcode pushing');
b = document.form1.barcode;
bs = document.form1.barcodes;
if (bs.value == "") {
bs.value = b.value;
} else { // ?? 111,333,444,... ???
bs.value = b.value;
}
}
Okay, you should be able to get the count using the keys values returned in reverse in brackets with the array.
Try the following and see if it works for you...
$ProductName = $ary[0]['ProductName'];
//--> get the count of your array
$count = count($ProductName);
//--> define an output variable to hold values
$output = null;
$i = 0;
//--> reduce count by one as key values start at 0 and count starts at 1
$count = $count - 1;
//--> subtraction and addition of $count by one to reduce warning
//--> of `undefined offset` for index on mismatched key values
while($count + 1){
//--> concatenate the values into a variable for display
$output .= $ProductName[$count];
//--> or push the reversed values back into an array
$product_name[$i] = $ProductName[$count];
//--> $product_name should now hold your values in reverse use a foreach
// use a foreach to display values in your table
$count--;
$i++;
}

Filter in array

I store dates in mysql databse in a date field like this......
09/03/2018|29/03/2018|17/06/2018|10/07/2018|28/10/2019|12/02/2019
In php I convert the above date formats into an array...
$currentyear= date("Y");
$this_month = array();
$other_month = array();
$dates_list = #explode("|", $dates_list);
$dates_list = str_replace(array("\r", "\n"), '', $dates_list);
foreach($dates_list as $date)
{
if(strstr($date,$month))
{
array_push($this_month,$date);
} else {
array_push($other_month,$date);
}
}
It's the $other_month array I wish to filter
So in the following array 09/03/2018|29/03/2018|17/06/2018|10/07/2018|28/10/2019|12/02/2019 it would only show the last two dates.
I would like to filter out all none "current year" dates, if anyone can help it would be greatly appreciated.
Thank you
I don't really prefer what you are doing DB wise, however to filter your array here is a script:
$this_year = [];
$other_years = [];
foreach ($dates_list as $date) {
if (date('Y', strtotime($date)) == date('Y')) {
$this_year[] = $date;
} else {
$other_years[] = $date;
}
}

How to add array inside array and call them out

Below is array stored in session. It works finely.
$_SESSION['cart'][$sum_1]=array('car_id'=>$car_id,'location'=>$location,'dropoff'=>$d_location,'date_value'=>$date_value,'date_value_2'=>$date_value_2,'total_days'=>$total_days,'addon'=>$addon);
?>
And I call them out like this,
foreach($_SESSION['cart'] as $total=>$id)
{
echo $total;
echo $id['addon'];
}
Now I want to add another array inside the above array to include date_from and date_to for
addon items ($id['addon']).
How can I do that and then call them out according to addon_id?
This is the part that stores addon items id in the array for now:
'addon'=>$addon
EDITED
$_SESSION['cart'][$sum_1]=array('car_id'=>$car_id,'location'=>$location,'dropoff'=>$d_location,'date_value'=>$date_value,'date_value_2'=>$date_value_2,'total_days'=>$total_days,'addon'=>$addon,array('d_from'=>$date_from,'d_to'=>$date_to))
This will give you the wanted output
foreach($_SESSION['cart'] as $total=>$id)
{
if ($id['addon'] == $wanted_addon_to_add_dates) {
$array['date_from'] = $date_from;
$array['date_to'] = $date_to;
$id[(whatever your want here)] = $array;
}
}
And just a suggestion to give more sense to your code.
It will gives you an array like
array ('var'=>value, ..., array ('addon'=>addon_id, 'date_from'=>date_from, 'date_to'=>date_to))
foreach($_SESSION['cart'] as $total=>$id)
{
if ($id['addon'] == $wanted_addon_to_add_dates) {
$array['date_from'] = $date_from;
$array['date_to'] = $date_to;
$array['addon'] = $id['addon'];
$id['addon'] = $array;
}
}
foreach($_SESSION['cart'] as $total=>$id)
{
echo $total;
foreach( $id['addon'] as $key=>$value)
{
echo "$key - $value";
}
}
I assumed the dates were in $addon already. If not you can just add a variable to the array you already have, like
$_SESSION['cart'][$sum_1]=array('car_id'=>$car_id,'location'=>$location,'dropoff'=>$d_location,'date_value'=>$date_value,'date_value_2'=>$date_value_2,'total_days'=>$total_days,'addon'=>$addon,'dates'=> array('d_from'=>$date_from,'d_to'=>$date_to))
or
$dates = array('d_from'=>$date_from,'d_to'=>$date_to);
$_SESSION['cart'][$sum_1]=array('car_id'=>$car_id,'location'=>$location,'dropoff'=>$d_location,'date_value'=>$date_value,'date_value_2'=>$date_value_2,'total_days'=>$total_days,'addon'=>$addon,'dates'=> $dates)
In that case you have to replace 'addon' with 'dates' in the first code example.

return indexes of the max values in an associative array in php [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Return index of highest value in an array
How can i return all the index of the max value.. for example a have this array that contains grades of students
$grade = array(
"anna" => "5",
"lala"=>"7",
"eni"=>"7",
i want to return the names of the student who have the max grade
in this case should print: lala
eni
You can use max() in order to find the higest value and then do array_keys() over it.
http://php.net/manual/en/function.max.php
http://php.net/manual/en/function.array-keys.php
E.g.
$grade = array(
"anna" => "5",
"lala"=>"7",
"eni"=>"7",
$max = max($grade); // $max == 7
array_keys($grade, $max);
it looks like a school exercise ...
Ok, you can write something like that:
$maxInd = -1;
foreach($grade as $name => $ind) {
if($ind > $maxInd) {
$maxInd = $ind;
$maxRes = array();
}
if($ind == $maxInd) {
$maxRes[] = $name;
}
}
return "The highest names are " . implode(', ',$maxRes);
please, let me know if it works!
you can do sth. like this:
$inversed = Array();
$highGrade = 0;
foreach ($grade AS $student=>$grade){
if (isset($inversed[$grade]))
$inversed[$grade][] = $student;
else
$inversed[$grade] = Array($student);
if ($grade > $highGrade) $highGrade = $grade;
}
print_r($inversed[$highGrade]);
<?php
$grade = array(
"atest" => 6,
"banna" => "5",
"lala"=>"7",
"eni"=>"7");
asort($grade);
$reverse = array_reverse($grade);
$prev_val='';
$counter = 0;
foreach($reverse as $key=>$value)
{
if((($counter==1)&&($value==$prev_val))||($counter==0))
{
echo $key."->".$value."<br/>";
$prev_val = $value;
$counter++;
}
}
?>
I have added one more element to the array to clear your doubt.

Categories