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!
3
Answers
If you want to search for a specific value in your array have you tried
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
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.Yields:
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 usingmin()
.you dont have mentioned what todo with prior dates, eg. searching for
'2022-12-07'
, how to tread2022-12-06
and2022-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 :