Spent a bit some time while trying to find native method in PHP that would allow me to search multidimensional array. Looks like PHP guys havn’t thought about it. I had no way but to write my own. If you guys have the same need you are free to use it.

$array = array([0] => array('color' => 'red'));
 
//search array example
array_search_exp($array,"shape=='circle' AND color=='blue'");
 
function array_search_exp($array, $expression, $as_indexes = false) {
	if($expression == '')
		return $array;
 
	if (!is_array($array) || !preg_match('/[a-z_][\w_]*(?:==|!=|>|<|>=|<=).+/', $expression))
		return null;
 
	$result = array();
	$expression = preg_replace("/([^\s]+?)(=|<|>|!)/", "\$a['$1']$2", $expression);
	foreach ( $array as $key => $a ) {
		if (eval( "return $expression;"))
		$result[] = ($as_indexes) ? $key : $a;
	}
 
	return (count($result) > 0) ? $result : null;
}

Dima Svirid

Software architect. Ajax/Javascript, HTML5, Android, iPhone/iPad, JAVA, PHP, Cold Fusion, SQL, Air, Flash, Open source software, Frameworks

More Posts

Follow Me:

Tagged with:
 

Leave a Reply