【发布时间】:2017-11-02 13:06:35
【问题描述】:
我在 php 中有以下数组,我试图在日期上进行过滤。日期以“Ymd”格式存储在 DropDate 键中。
我想在 Dropdate
array(3) {
[0]=>
array(30) {
["Id"]=>
int(18762)
["DropDate"]=>
string(8) "20171101"
}
[1]=>
array(30) {
["Id"]=>
int(18760)
["DropDate"]=>
string(8) "20171102"
}
[2]=>
array(30) {
["Id"]=>
int(18258)
["DropDate"]=>
string(8) "20171102"
}
}
我使用了以下代码,但是当我对其进行 json_encode 编码时,它会添加 [{0:"Id":18280,"...]。
$records = array_filter($bookings, function($value) {
$todays_date = date('Ymd');
return $value['DropDate'] < (int)$todays_date;
});
我不确定如何针对 dropdate 字段的小于值执行 array_search。
$todays_date = date('Ymd');
if(($key = array_search($todays_date, array_column($student,'DropDate'))) !== false) {
unset($student[$key]);
}
然后,当我执行 json_encode 以将其返回到我的应用程序时,我得到了奇怪的行为,例如它在每个对象的前面添加了 0 和 1。
[{"0":{"Id":18280,"DropDate":"20171030"},"1":{"Id":18284,"DropDate":"20171101"}}]
我的应用程序期望这个没有 0 或 1
[{"Id":18280,"DropDate":"20171030"},{"Id":18284,"DropDate":"20171101"}]
【问题讨论】:
-
我不确定问题出在哪里,据我所知,它为您提供了所需的记录。如果只需要日期,可以使用
array_map修改生成的结构。 -
在你的数组中,
DropDate似乎是一个字符串,你应该在return $value['DropDate'] < (int)$todays_date;测试之前将其转换为整数,也许你的结果不一致? -
谢谢,我应该提到当我对过滤后的数组进行 json_encode 时,我得到 [{"0":{"Id":18280,"DropDate":"20171030"},"1": {"Id":18284,"DropDate":"20171101"}}] 我的应用程序期望的是 [{"Id":18280,"DropDate":"20171030"},"1":{"Id":18284, "DropDate":"20171101"}]
-
@snowflakes74 你预期的数组仍然有一个
"1":这是你真正想要的,还是一个错字? -
在json_encode之前调用
$arr = array_values($arr);