I need to filter some $data array with multiple conditions.
My code:
public static function filterTable(array $data, $conditions) : array {
$data = array_filter($data, function ($row) use ($conditions) {
if ($row["check_id"] == 0) {
var_dump(['$row'=> $row], self::validateData($row, $conditions, null, 0));
die();
}
return self::validateData($row, $conditions, null, 0);
});
return $data;
}
public static function validateData($row, $conditions, $res, $i) : bool {
if ($res !== null) {
$tempRes = self::compare($row[$conditions[$i]["column"]], $conditions[$i]["value"], $conditions[$i]["condition"]);
$res = self::logicalOp($res, $tempRes, $conditions[$i-1]["operator"]);
} else {
$res = self::compare($row[$conditions[$i]["column"]], $conditions[$i]["value"], $conditions[$i]["condition"]);
}
if (!empty($conditions[$i]["operator"])) {
self::validateData($row, $conditions, $res, ++$i);
}
if ($row["check_id"] == 0) {
var_dump(["validateDataFunc" => $row, $res]);
die();
}
return $res;
}
public static function logicalOp($val1, $val2, string $op) {
switch ($op) {
case "||":
return ($val1 || $val2);
case "&&":
return ($val1 && $val2);
default:
return true;
}
}
public static function compare($val1, $val2, string $op) : bool {
switch ($op) {
case "=":
return $val1 == $val2;
case "!=":
return $val1 != $val2;
case ">=":
return $val1 >= $val2;
case "<=":
return $val1 <= $val2;
case ">":
return $val1 > $val2;
case "<":
return $val1 < $val2;
default:
return true;
}
}
If you output the result of the function via var_dump in the validateData
function, then the return value is false
(which is what you want). But, if you display the result of calling the function itself (in filterTable
function), you get true
at the output.
Please note that I display the result of execution for the same array element.
Result into validateData
function:
array(2) {
["validateDataFunc"]=>
array(16) {}
[0]=>
bool(false)
}
Result into filterTable
function:
array(1) {
["$row"]=>
array(16) {}
}
bool(true)
I hope you'll give me some tips on how to improve my code.
Help me if u can do this, maybe I have too stupid mistake:)
Thanks
SOLUTION:
Add return to recursive call
public static function validateData($row, $conditions, $res, $i) : bool {
if ($res !== null) {
$tempRes = self::compare($row[$conditions[$i]["column"]], $conditions[$i]["value"], $conditions[$i]["condition"]);
$res = self::logicalOp($res, $tempRes, $conditions[$i-1]["operator"]);
} else {
$res = self::compare($row[$conditions[$i]["column"]], $conditions[$i]["value"], $conditions[$i]["condition"]);
}
if (!empty($conditions[$i]["operator"])) {
return self::validateData($row, $conditions, $res, ++$i); //here
}
return $res;
}