|
Posted by Toby A Inkster on 11/17/07 18:34
Thomas Mlynarczyk wrote:
> I have two arrays like this:
>
> $aSearch = array( 'A', 'B', 'C.D', 'E', 'F' );
> $aSubject = array( 'A' => 0, 'A.B' => 1, 'X' => 2, 'C.D.E' => 3, 'A.B.C' =>
> 4 );
>
> Now I want to search $aSubject for the longest key that consists of the
> first x elements of $aSearch concatenated by "." (where x = 1...count(
> $aSearch ) ). In other words, he algorithm involved should check for the
> existence of the following keys in $aSubject:
>
> A
> A.B
> A.B.C.D
> A.B.C.D.E
> A.B.C.D.E.F
>
> and return the longest match - in the example 'A.B'.
foreach ($aSearch as $a)
{
$key = $a;
while (strlen($key) && !isset($aSubject[$key]))
$key = preg_replace('/\.?[^\.]*$/', '', $key);
if (strlen($key))
printf("Searched for '%s'. Closest match was '%s', value %s.\n",
$a,
$key,
$aSubject[$key]);
else
printf("Searched for '%s'. No matching key found.\n", $a);
}
A bit cleaner to use a function:
function array_component_search ($needle, &$haystack, &$value=NULL)
{
$key = $needle;
while (strlen($key) && !isset($haystack[$key]))
$key = preg_replace('/\.?[^\.]*$/', '', $key);
$value = strlen($key) ? $haystack[$key] : NULL;
return strlen($key) ? $key : FALSE;
}
foreach ($aSearch as $a)
{
$key = array_component_search($a, $aSubject, $value);
if ($key!==FALSE)
printf("Searched for '%s'. Closest match was '%s', value %s.\n",
$a,
$key,
$value);
else
printf("Searched for '%s'. No matching key found.\n", $a);
}
Note that array_component_search takes two required arguments:
$needle = Key you're searching for a close match for.
$haystack = Lookup array.
The closest matching key is returned by the function, and as a side-effect,
the value for that key may be placed in a variable passed to the function
as a third argument.
Helpful?
--
Toby A Inkster BSc (Hons) ARCS
[Geek of HTML/SQL/Perl/PHP/Python/Apache/Linux]
[OS: Linux 2.6.12-12mdksmp, up 11 days, 1:11.]
[Now Playing: ./stereophonics/handbags_and_gladrags.ogg.]
Belgium
http://tobyinkster.co.uk/blog/2007/11/17/belgium/
Navigation:
[Reply to this message]
|