我有一个Laravel项目,并且具有JSON文件,想在数组的第3级中进行搜索,并在日期数组范围内返回数组的第1级
我使用此功能:
public function search3($array, $key, $value){
$results = array();
if (is_array($array)) {
if (isset($array[$key]) && $array[$key] == $value) {
$results[] = $array;
}
foreach ($array as $subarray) {
$results = array_merge($results, self::search3($subarray, $key, $value));
}
}
return $results;
}
返回结果,但不给我这个数组
我希望函数返回该数组的父级的父级:
答案 0 :(得分:0)
我希望我正确理解了这一点;我认为您想在数组的第三层中搜索“开始” +日期或“结束” +日期组合,然后返回与“匹配”数据相匹配的酒店(位于匹配数据上方两层)给定的组合。
怎么样?
function search3($hotels, $key, $value){
$results = array();
foreach ($hotels as $hotelKey => $hotelProperties) {
foreach ($hotelProperties['availability'] as $availabilityKey => $range) {
if (isset($range[$key]) && $range[$key] == $value) {
$results[$hotelKey] = $hotels[$hotelKey];
}
}
}
return $results;
}
更新以查找在给定日期范围内(从开始到结束)的可用酒店:
function search3($hotels, $from, $to){
$format = 'd-m-Y';
$from = DateTime::createFromFormat($format, $from);
$to = DateTime::createFromFormat($format, $to);
$results = array();
foreach ($hotels as $hotelKey => $hotelProperties) {
foreach ($hotelProperties['availability'] as $range) {
$availableFrom = DateTime::createFromFormat($format, $range['from']);
$availableTo = DateTime::createFromFormat($format, $range['to']);
if ($from >= $availableFrom && $to <= $availableTo) {
$results[$hotelKey] = $hotelProperties;
}
}
}
return $results;
}