|
Posted by Thomas Mlynarczyk on 11/17/07 21:50
Also sprach Toby A Inkster:
> 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);
> }
This finds $aSubject['A'], but should find $aSubject['A.B'].
If I remove the foreach and put an
$a = implode( '.', $aSearch )
at the beginning, it will find $aSubject['A.B.C']. (Because, in the imploded
form, the information that 'C.D' is "indivisible" gets lost.)
Maybe I was not clear enough describing my problem. The algorithm should be
something equivalent to
$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 );
1)
Convert $aSearch somehow to
$aSearch =array(
'A.B.C.D.E.F',
'A.B.C.D.E',
'A.B.C.D',
'A.B', // Note: no 'A.B.C', as 'C.D' is "indivisible"
'A'
)
2)
foreach ( $aSearch as $sKey )
{
if ( array_key_exists( $sKey, $aSubject ) ) { echo "Found
$aSubject[$sKey]"; break; }
}
Meanwhile I've come up with this:
for ( $tmp = array(), $i = 0; $i < count( $aSearch ); $i++ )
{
$tmp[$i] = $i ? $tmp[ $i - 1 ] . '.' . $aSearch[$i] : $aSearch[$i];
}
foreach ( array_reverse( $tmp, true ) as $sKey )
{
if ( array_key_exists( $sKey, $aSubject ) ) { echo "Found
$aSubject[$sKey]"; break; }
}
But it does not look elegant/efficient enough to me.
Greetings,
Thomas
--
C'est pas parce qu'ils sont nombreux à avoir tort qu'ils ont raison!
(Coluche)
Navigation:
[Reply to this message]
|