Last active
June 29, 2018 23:36
-
-
Save mkhizeryounas/2a894d4e8122628d66b4c9ac93927aa8 to your computer and use it in GitHub Desktop.
Filter 1-D PHP array with custom filters.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Author: @mkhizeryounas | |
* @array : 1-D Array | |
* @rules : | |
* { | |
* "filter" : [ | |
* { | |
* "key" : "product_id", | |
* "value" : "10593", | |
* "op" : "<" | |
* } | |
* ] | |
* } | |
*/ | |
function sd_filter($array, $rules=[]) { | |
if(!is_array($rules)) $rules = []; | |
$resArr = []; | |
foreach($array as $key => $val) { | |
$check = true; | |
foreach($val as $dataKey => $dataVal) { | |
$onceWrong = false; | |
foreach($rules as $ruleKey => $ruleVal) { | |
if( | |
!isset($ruleVal['key']) || | |
!isset($ruleVal['value']) || | |
!isset($ruleVal['op']) | |
) continue; | |
if($dataKey === $ruleVal['key']) { | |
if($ruleVal['op'] === "==") { // equal op | |
if($dataVal == $ruleVal['value']) { | |
$check = true; | |
continue; | |
} | |
else { | |
$onceWrong = true; | |
$check = false; | |
break; | |
} | |
} | |
else if($ruleVal['op'] === "!=") { // not equal op | |
if($dataVal != $ruleVal['value']) { | |
$check = true; | |
continue; | |
} | |
else { | |
$onceWrong = true; | |
$check = false; | |
break; | |
} | |
} | |
else if($ruleVal['op'] === ">") { // Greater than | |
if(floatval($dataVal) > floatval($ruleVal['value'])) { | |
$check = true; | |
continue; | |
} | |
else { | |
$onceWrong = true; | |
$check = false; | |
break; | |
} | |
} | |
else if($ruleVal['op'] === "<") { // less than | |
if(floatval($dataVal) < floatval($ruleVal['value'])) { | |
$check = true; | |
continue; | |
} | |
else { | |
$onceWrong = true; | |
$check = false; | |
break; | |
} | |
} | |
else if($ruleVal['op'] === "<=") { // less than equal | |
if(floatval($dataVal) <= floatval($ruleVal['value'])) { | |
$check = true; | |
continue; | |
} | |
else { | |
$onceWrong = true; | |
$check = false; | |
break; | |
} | |
} | |
else if($ruleVal['op'] === ">=") { // greater than equal | |
if(floatval($dataVal) >= floatval($ruleVal['value'])) { | |
$check = true; | |
continue; | |
} | |
else { | |
$onceWrong = true; | |
$check = false; | |
break; | |
} | |
} | |
} | |
} | |
if($onceWrong) break; | |
} | |
if($check) { | |
array_push($resArr, $val); | |
} | |
} | |
return $resArr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment