Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
* This function recursively searches the JSON API and picks out the
* specified items based on the parameters passed into the function
* @param array $data
* @param string $needle
* @param string $catNeedle
* @return array
public function RecursiveDataFilter(array $data, $needle, $catNeedle = null)
// Check to make sure $data is passed in as an array
// if not an array, error string is returned
if (!is_array($data))
$result = 'Error! Error retrieving proper stats in an array!';
return $result;
// Initializing two arrays, one to hold a reduced haystack, the other to hold results
$results = array();
$haystack = array();
// Checks to see if a category needle was passed in
if ($catNeedle)
// Foreach loop going through each key => value combination of $data
foreach ($data as $catKey => $catValue)
// Checks to see if the given index is equivalent to the category needle
if ($catKey == $catNeedle)
// Checks to see if the desired needle exists within the category
if (is_array($catValue) && array_key_exists($needle, $catValue))
// Found the key, now assigning and returning the result.
echo "Key Found! Assigning results to the return array.<br />";
$results = $catValue[$needle];
return $results;
// Breaks out of the foreach loop with or without a result
// if it hasn't found the category needle the haystack is reduced
// Checks to see if its an array
// creates a reduced haystack from available, searchable arrays
$haystack = array_merge($haystack, $catValue);
// if $results is empty, prepare to recurse
// Sets $data equal to $haystack to conserve memory
$data = $haystack;
// nulls out $haystack to recycle resources
$haystack = null;
// intializes the recursion for the next iteration around
$results = $this->RecursiveDataFilter($data, $needle, $catNeedle);
// return results whether they're null or not
return $results;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment