Find values recursively inside complex json objects in PHP

A PHP function to to quickly search complex, nested php structures for specific values.

Dicembre 18, 2022

This function lets you traverse any php object made of arrays and objects to find properties (of objects) or keys (of arrays) that match a particular values and returns an array of the matches.

It is recursive.

Recursion is a programming concept which involves a function calling itself repeatedly until a certain condition is met. It is a powerful technique used in programming to solve problems that can be broken down into smaller, repeating sub-problems. Recursion is a way to succinctly describe a large problem in a few lines of code. A recursive function has a base case, which is a simple condition that will terminate the recursion, and a recursive case, which is a condition that will cause the function to call itself again. When the base case is met, the recursion will end and the result of the function will be returned.

The find_recursive function

This function can be used to quickly and easily search complex, nested php structures for specific values, allowing you to quickly locate the information you need.

	function find_recursive($obj, $key) {
		$found = array();
	  if ( is_object($obj) ) {
		foreach ($obj as $property => $value) 
			if($property === $key) $found[] = $value;
			elseif (is_array($value) || is_object($value)) 
				$found = array_merge( $found,  find_recursive($value, $key) );

	  } elseif ( is_array($obj) ) {
		foreach ($obj as $keyar => $value) 
			if($keyar === $key) $found[] = $value;
			elseif (is_array($value) || is_object($value)) 
				$found = array_merge( $found,  find_recursive($value, $key) );
	  }
	  return $found;
	}

It has been used in the Minibots.class.php freely available on Github that is a PHP class that helps developing spiders and bots.

$obj is the big object that you want to scan, and $key is the name of the properties or the array key of the object that you want to extract.

Author

PHP expert. Wordpress plugin and theme developer. Father, Maker, Arduino and ESP8266 enthusiast.