Monday, October 24, 2011

PHP - function to search an associative array

To find the value of part of an associative array such as the one below, the function below will search for a term within the key that is specified in the function...

$arr = "Array ( [0] => Array ( [id] => 1 [date] => 2011-10-18 [details] => Shopping ) [1] => Array ( [id] => 2 [date] => 2011-10-01 [details] => Tax ) [2] => Array ( [id] => 123 [date] => 2011-10-18 [details] => Petrol )";



function getKeys($arr,$search){
foreach($arr as $keys=>$values)
{
foreach ($values as $key => $value) {
if($key=="date" && $value==$search){//$key=="date" can be any key from the array
$getkeys.=$keys.",";
}
}
}
$len=strlen($getkeys)-1; //get the length of $getkeys
$getkeys=substr($getkeys,0,$len); //remove the last comma
$getkeys=$pieces = explode(",", $getkeys); //make an arrayof the keys
return $getkeys;
}//end function getKeys

$getkeys=getKeys($arr,"2011-10-18");//search term can be anything, here it is a date
print_r($getkeys);//print the array


This will return an array of the keys of the elements of the array in which the search term was found. In this case Array ( [0] => 0 [1] => 2 )

No comments: