按元素

时间:2017-04-04 11:45:07

标签: php arrays array-filter

下面是数组内部循环: 我想通过[date-begin]和[date-end]过滤这个数组 例如,如果我发布startdate = 2015-06-29和enddate = 2015-08-29 然后应该在这个范围之间的数组数据。

我试过了:

1. array_slice 
2.foreach(range ($startdate,$enddate) as $data){
                            echo "Age: {$data}<br />";
                        }
Array
(
    [name] => MCLE 201
    [date-begin] => 2015-06-29
    [date-end] => 2015-06-29

)
Array
(
    [name] => MCLE 201
    [date-begin] => 2015-07-29
    [date-end] => 2015-07-29

)
Array
(
    [name] => MCLE 201
    [date-begin] => 2015-08-29
    [date-end] => 2015-08-29

)
Array
(
    [name] => MCLE 201
    [date-begin] => 2015-09-29
    [date-end] => 2015-09-29

)

3 个答案:

答案 0 :(得分:1)

@Aashi你可以用foreach()完成它,如下所示:

<?php
  $yourArray = array(
                array(
                    "name" => "MCLE 201",
                    "date-begin" => "2015-06-29",
                    "date-end" => "2015-06-29"

                ),
                array(
                    "name" => "MCLE 201",
                    "date-begin" => "2015-07-29",
                    "date-end" => "2015-07-29"

                ),
                array(
                    "name" => "MCLE 201",
                    "date-begin" => "2015-08-29",
                    "date-end" => "2015-08-29"

                ),
                array(
                    "name" => "MCLE 201",
                    "date-begin" => "2015-09-29",
                    "date-end" => "2015-09-29"

                )
              );
$startdate = "2015-06-29";
$enddate = "2015-08-29";
$filteredArr = array();
foreach($yourArray as $value) {
      if($startdate <= $value["date-begin"] && $enddate >= $value["date-end"]){
        $filteredArr[] = $value;
      }
}
echo "<pre>";
print_r($filteredArr);

答案 1 :(得分:1)

试试这个:

name

Click here to check output

答案 2 :(得分:0)

这是你问题的正确解决方案!

function date_is_between($start_date, $end_date, $date){
    $start_date = date('Y-m-d',strtotime($start_date));
    $end_date  = date('Y-m-d',strtotime($end_date));
    $date = date('Y-m-d',strtotime($date));
    $match = FALSE;

    if (($date => $start_date) && ($date <= $end_date))
        $match = TRUE;

    return $match;
}

function date_between($element, $start_date, $end_date)
{
    $match = FALSE

        if(date_is_between($element['date-begin'],  $element['date-end'], $element['date-begin']) && date_is_between($element['date-begin'],  $element['date-end'], $element['date-end']))
            $match = TRUE;

    return $match;
}

$filter_array = array_filter($data, "date_between");