如果与$array ['date ']中值不相同,我想从$search_date中获取最接近日期如果与$array ['date']中值相同,我想获取所有数组
- 日期格式为'Y-m-d'。
例一:
$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"}]
例二:
$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"}]
例三:
$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"}]
例四:
$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"}]
谢谢你,谢谢你
3条答案
按热度按时间knpiaxh11#
此代码计算
$search
与每条记录之间的距离(以天为单位)。它假定您要查找未来和过去的最近距离。产量:
如果您只想搜索将来最接近的日期,则需要删除
abs()
函数,然后在使用min()
之前删除$distances
数组中的所有负项。5sxhfpxr2#
如果要在数组中搜索特定值,您是否尝试过
通过这个你可以在数组中搜索一个特定的值
如果要搜索最低值
尝试对数组进行for循环,检查数组是否小于前一个索引,如果for循环已经结束,则得到最小的日期
yhqotfr83#
您没有提到如何处理之前的日期,例如,搜索
'2022-12-07'
,如何处理2022-12-06
和2022-12-08
,因为两者的差都是1。您可以计算每个条目的datediff,获取最小datediff并使用此datediff输出元素。例如: