Last active
December 7, 2015 15:56
-
-
Save Ikke/12e64dfaf18902582837 to your computer and use it in GitHub Desktop.
Filter recursive
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 | |
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