2017-04-04 120 views
-1

下面是循環內的數組: 我想通過[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 

) 
+0

看看array_filter或嘗試foreach –

回答

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); 
+0

謝謝。這工作:) – Aashi

1

試試這個:

$filterArray = array(); 
foreach($arr as $key=>$val){ 
    if(strtotime($val['date-begin']) >= strtotime($postedDateBegin) && strtotime($val['date-end']) <= strtotime($postedDateEnd)){ 
     $filterArray[] = $val; 
    } 
} 

Click here to check output

+0

謝謝。這工作:) – Aashi

+0

@Aashi,如果這個工作,你能接受這個答案。鼓勵其他開發者也是一種很好的做法。快樂的編碼。 :) – Bhaskar

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");