Skip to content

Instantly share code, notes, and snippets.

@Ikke
Last active December 7, 2015 15:56
Show Gist options
  • Save Ikke/12e64dfaf18902582837 to your computer and use it in GitHub Desktop.
Save Ikke/12e64dfaf18902582837 to your computer and use it in GitHub Desktop.
Filter recursive
<?php
function filter_recursive($data, $predicate = null)
{
if ($predicate == null) {
$predicate = function ($value) { return !empty($value); };
}
$is_object = false;
if (is_object($data)) {
$is_object = true;
$data = (array) $data;
}
$filtered_data = array();
foreach($data as $key => $value) {
if (is_array($value) || is_object($value)) {
$result = filter_recursive($value, $predicate);
if (!empty($result)) {
$filtered_data[$key] = filter_recursive($value, $predicate);
}
} elseif ($predicate($value)) {
$filtered_data[$key] = $value;
}
}
if ($is_object) {
return (object) $filtered_data;
} else {
return $filtered_data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment