phparraysfiltering

Filter a 2d array (query result set) by multiple conditions


Is there any solutions out there, that make it possible to search in a query.

Example:

I've this simple query:

$this->db->where('start >=',time());
$this->db->where('end <=',strtotime("+1 month"));
$result = $this->db->get('bookings');

What I then want it to be able to make a search that looks like my query above, but which doesn't search in the database, but in the $result results.

So it should be possible to do something like:

$where = array(
  'start >=' => time(),
  'end <=' => strtotime("+1 day")
);
$get_result_info_by_search = $this->Search_model->get_stored_results($result, $where);

The goal is to reduce the number of calls to the database, because my interval is always the same (I loop through a date range and make the same call for instance 31 times (if 31 days)


Solution

  • This can be done quite easily by looping through the rows and testing 'start' and 'end' values.

    /**
     * @param CI_DB_result instance $result
     * @param array $where with two keys, 'start' and 'end', containing timestamp values, ie. 
     * $where = ['start' => time(), 'end' => strtotime("+1 month"));
     * @return mixed An array of db row objects or NULL if nothing matches
     */
    public function get_stored_results($result, $where)
    {
        $rows = $result->result();
        foreach ($rows as $row)
        {
            if($row->start >= $where['start'] && $row->end <= $where['end'])
            {
                $matches[] = $row;
            }
        }
        return isset($matches) ? $matches : NULL;
    }
    

    If you would rather get back an array of row arrays

    public function get_stored_results($result, $where)
    {
        $rows = $result->result_array();
        foreach ($rows as $row)
        {
            if($row['start'] >= $where['start'] && $row['end'] <= $where['end'])
            {
                $matches[] = $row;
            }
        }
        return isset($matches) ? $matches : NULL;
    }