Skip to content

Instantly share code, notes, and snippets.

@photoup-godwinh
Created June 20, 2018 16:29
Show Gist options
  • Save photoup-godwinh/264e1c98e400decea3fbaea0ef75280e to your computer and use it in GitHub Desktop.
Save photoup-godwinh/264e1c98e400decea3fbaea0ef75280e to your computer and use it in GitHub Desktop.
Laravel array_only_recursive
/**
* matches a string to an array of key-patterns
* @param $string - the string to match
* @param $keys - array of key-patterns. can a a simple string key, dot-notated key, a wilcard key
* @return boolean
*
* usage:
* match_key_patterns('person.name', ['person.name', 'person.age', 'account.*']) => returns TRUE as person.name matches a value in the keys
* match_key_patterns('person.bday', ['person.name', 'person.age', 'account.*']) => returns FALSE as person.bday did not match a value in the keys
* match_key_patterns('account.password', ['person.name', 'person.age', 'account.*']) => returns TRUE as account.password matches a wilcard key pattern which is account.*
*/
function match_key_patterns($string, $keys) {
foreach($keys as $key) {
$re_str = preg_replace('/\./', '\\.', $key);
$re_str = preg_replace('/\\*/', '(.+)', $re_str);
$pattern = '#^(' . $re_str. ')$#';
if(preg_match($pattern, $string)) {
return true;
}
}
return false;
}
/**
* performs an array_only recursively.
* usage: similar to array_only except $keys will always be an array
* @param $data - the array to be filtered
* @param $keys - the keys to filter
* @return array
*/
function array_only_recursive($data, array $keys) {
$result = [];
if(!is_array($data)) {
return [];
}
foreach($data as $key => $value) {
$curr_key = [];
$parent_keys = func_get_arg(2);
if($parent_keys !== FALSE) $curr_key[] = $parent_keys;
$curr_key[] = $key;
$curr_key = implode('.', $curr_key);
if(in_array($key, $keys, true)) {
array_set($result, $curr_key, $value);
} else {
if(match_key_patterns($curr_key, $keys)) {
array_set($result, $curr_key, $value);
} else {
$result = array_replace_recursive($result,
array_only_recursive($value, $keys, $curr_key));
}
}
}
return $result;
}
/**
Usage:
$data = [
'account' => [
'email' => '[email protected]',
'username' => 'justmyuser'
],
'profile' => [
'name' => 'John Doe',
'bday' => '1990-01-01',
'country' => 'United States'
]
];
array_only_recursive($data, ['*']);
// return: exactly the content of $data
array_only_recursive($data, ['account.email', 'profile.name']);
// return: ['account' => ['email' => '[email protected]'], 'profile' => ['name' => 'John Doe']]
array_only_recursive($data, ['account.username', 'profile.*']);
// return: ['account' => ['username' => 'justmyuser'], 'profile' => [
'name' => 'John Doe',
'bday' => '1990-01-01',
'country' => 'United States'
]]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment