Skip to content

Instantly share code, notes, and snippets.

@ELD
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ELD/3dfc475d83d52dd4e558 to your computer and use it in GitHub Desktop.
Save ELD/3dfc475d83d52dd4e558 to your computer and use it in GitHub Desktop.
<?php
/**
* 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
break;
}
// if it hasn't found the category needle the haystack is reduced
else
{
// Checks to see if its an array
if(is_array($catValue))
{
// creates a reduced haystack from available, searchable arrays
$haystack = array_merge($haystack, $catValue);
}
}
}
// if $results is empty, prepare to recurse
if(!$results)
{
// 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