Created
September 28, 2019 16:16
-
-
Save ADCPD/a00df3f44b96322fbd6818f216e9d982 to your computer and use it in GitHub Desktop.
Filter in array using one or many params
This file contains hidden or 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
<?php | |
/** | |
* If one or more params[] element exists in data[]. | |
* Our function will return the elements conserner | |
*/ | |
$params = [ | |
"nom" => 'titof', | |
"prenom" => 'edoe', | |
"age" => '25' | |
]; | |
$data = [ | |
0 => [ | |
'nom' => 'john', | |
'prenom' => 'doe', | |
'age' => '25' | |
], | |
1 => [ | |
'nom' => 'lola', | |
'prenom' => 'la grandi', | |
'age' => '72' | |
], | |
2 => [ | |
'nom' => 'michael', | |
'prenom' => 'Pamal', | |
'age' => '25' | |
] | |
]; | |
function getFilteredArray($params, $data) { | |
$filtredArray = []; | |
foreach($params as $key => $value) { | |
foreach($data as $index => $item) { | |
if(array_key_exists($key, $item) && in_array($value, $params)) { | |
if($item[$key] == $value ){ | |
$filtredArray[$index] = $item; | |
} else { | |
continue; | |
} | |
} | |
} | |
} | |
return $filtredArray; | |
} | |
var_dump(getFilteredArray($params, $data)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment