根据参数过滤多维数组?

时间:2011-11-02 21:26:44

标签: php arrays date filter

我正在尝试在start_date和结束日期过滤更多内容。

   <?php 
        /* 
         * filtering an array 
         */ 
        function filter_by_value ($array, $index, $value){ 
            if(is_array($array) && count($array)>0)  
            { 
                foreach(array_keys($array) as $key){ 
                    $temp[$key] = $array[$key][$index]; 

                    if ($temp[$key] == $value){ 
                        $newarray[$key] = $array[$key]; 
                    } 
                } 
              } 
          return $newarray; 
        } 
    ?> 

示例:

<?php 
$results = array (
  0 => 
  array (
    'a' => 'U/H',
    'b' => 'Modification',
    'date' => '02/11/11',
    'h' => '17:15:13',
    'fullname' => 'First1 Name1',
    'desc' => 'Descript ',
  ),
  1 => 
  array (
    'a' => 'J/M',
    'b' => '',
    'date' => '03/11/11',
    'h' => '17:18:27',
    'fullname' =>  'First1 Name1',
    'desc' => 'Descript more '
  ),
);

$nResults = filter_by_value($results, 'fullname', 'First1 Name1'); 
echo '<pre>'; 
print_r($nResults); 
echo '</pre>'; 


Array
(
    [0] => Array
        (
            [a] => U/H
            [b] => Modification
            [date] => 02/11/11
            [h] => 17:15:13
            [fullname] => First1 Name1
            [desc] => Descript 
        )

    [1] => Array
        (
            [a] => J/M
            [b] => 
            [date] => 03/11/11
            [h] => 17:18:27
            [fullname] => First1 Name1
            [desc] => Descript more 
        )

)

For Now我想过滤该函数可以通过start_date和end_date

进行过滤

所以我改变了

function filter_by_value ($array, $index, $value,$start_date,$end_date)

任何人都可以在日期内过滤?

1 个答案:

答案 0 :(得分:1)

我总是将时间数据转换为时间戳,因此您可以轻松计算所有内容,转换为时间戳后,它只是基本的数学。

你的新功能看起来像这样:

<?php 
function filter_by_date($array, $index, $start_date, $end_date) {
      $newarray = array();
      if(is_array($array) && count($array)>0)  
        { 
            $start_time = strtotime($start_date); //make sure your date is written as  
            $end_time = strtotime($end_date);     // dd/mm/YYYY, will also work with           
                                                 //hours etc

            foreach(array_keys($array) as $key){ 
                $temp[$key] = strtotime($array[$key][$index]); //$index will be date

                if ($temp[$key] >= $start_time && $temp[$key] <= $end_time ){ 
                    $newarray[$key] = $array[$key]; 
                } 
            } 
          } 
      return $newarray; 
}

?>

对于其他符号等,最好检查php.net上的strtotime()页面! http://www.php.net/manual/en/function.strtotime.php

当然,您也可以在同一个函数中创建它,因此您不必编写更多函数:

if ($index == ('date' || 'h')) {
   //the content of filter by date, or the function itself
} else {
   //the content of your first function
}