Problem
Based on user-inputted fields ('title'
, 'note'
, 'due-date'
, 'priority'
, & 'course'
), I am filtering the $tasks
array which holds Task
objects. Based on the user-inputted field(s) (the user can either fill out 1 field or multiple), getSearchResults()
is suppose to filter $tasks
and return an array of Task
objects (i.e. $filtered_tasks
) that match all those search criteria (so it's an AND kind of search).
However, I'm getting the error 'Undefined variable: value'
because I'm using the variable $value
for the function in array_filter()
. My question is, how do I make it so I can use the variable $value
in the array_filter()
? Or what other function can I use to filter my array of Task
objects by certain criteria?
Code
function getSearchResults($tasks){
$search_fields = getSearchFields();
$filtered_tasks = $tasks;
foreach($search_fields as $field => $value){
//Filter array based on field
if($field === 'title'){
$filtered_tasks = array_filter($filtered_tasks, function($obj) {
return ($obj->title === $value);
});
}
if($field === 'note'){
$filtered_tasks = array_filter($filtered_tasks, function($obj) {
return ($obj->note === $value);
});
}
if($field === 'due-date'){
$filtered_tasks = array_filter($filtered_tasks, function($obj) {
return ($obj->due_date === $value);
});
}
if($field === 'priority'){
$filtered_tasks = array_filter($filtered_tasks, function($obj) {
return ($obj->priority === $value);
});
}
if($field === 'course'){
$filtered_tasks = array_filter($filtered_tasks, function($obj) {
return ($obj->course === $value);
});
}
}
return $filtered_tasks;
}
function getSearchFields(){
$search_fields = array();
if(!empty($_POST['title'])){
$search_fields['title'] = $_POST['title'];
}
if(!empty($_POST['note'])){
$search_fields['note'] = $_POST['note'];
}
if(!empty($_POST['due-date'])){
$search_fields['due-date'] = $_POST['due-date'];
}
if($_POST['priority'] !== ''){
$search_fields['priority'] = $_POST['priority'];
}
if($_POST['course']!==''){
$search_fields['course'] = $_POST['course'];
}
return $search_fields;
}
class Task{
public $title;
public $due_date;
public $priority;
public $course;
public $note;
function __construct($title, $due_date, $priority, $course, $note) {
$this->title = $title;
$this->due_date = $due_date;
$this->priority = $priority;
$this->course = $course;
$this->note = $note;
}
public function is_empty(){
return ($this->title === '' || $this->due_date === '' || $this->priority === '' || $this->course ==='' || $this->note ==='');
}
}