[PHP] Recursieve functie:oneindig, wat doe ik fout

Pagina: 1
Acties:

  • drm
  • Registratie: Februari 2001
  • Laatst online: 09-06-2025

drm

f0pc0dert

Topicstarter
Deze functie moet recursief een array of object doorlopen om een str_replace uit te voeren.
PHP:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?
function r_replace ( $needle, $str, $haystack )
{
   if ( is_array ( $haystack ) )
   {
      for ( $a = 0; $a < count ( $haystack ); $a++ )
         $haystack [ $a ] = r_replace ( $needle, $str, $haystack [ $a ] );
   }
   elseif ( is_object ( $haystack ) )
   {
      $v = get_object_vars ( $haystack );
      while ( list ( $prop, $value ) = each ( $v ) )
         $haystack->$prop = r_replace ( $needle, $str, $value );
   }
   else
      $haystack = str_replace ( $needle, $str, $haystack );

   return $haystack;
}
?>

Maar er blijkt dat wanneer ik deze functie aanroep met een array hij oneindig blijft lopen. What the heck doe ik fout :?

Misschien maak ik wel een hele grove fout, maar op dit moment zit ik ff vast, ik zie het niet ... wie helpt :)

Music is the pleasure the human mind experiences from counting without being aware that it is counting
~ Gottfried Leibniz


  • drm
  • Registratie: Februari 2001
  • Laatst online: 09-06-2025

drm

f0pc0dert

Topicstarter
Ik ben er al uit:

Ik had geen rekening gehouden met associatieve arrays.

Dit is 'm geworden:
PHP:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?
function r_replace ( $needle, $str, $haystack )
{
   if ( is_string ( $haystack ) )
      $haystack = str_replace ( $needle, $str, $haystack );
   elseif ( is_array ( $haystack ) )
      while ( list ( $a, $value ) = each ( $haystack ) ) // <-- let op!
         $haystack [ $a ] = r_replace ( $needle, $str, $value );
   elseif ( is_object ( $haystack ) )
   {
      $v = get_object_vars ( $haystack );
      while ( list ( $prop, $value ) = each ( $v ) )
         $haystack->$prop = r_replace ( $needle, $str, $value );
   }

   return $haystack;
}
?>

Music is the pleasure the human mind experiences from counting without being aware that it is counting
~ Gottfried Leibniz


  • Creepy
  • Registratie: Juni 2001
  • Laatst online: 21:46

Creepy

Tactical Espionage Splatterer

Hiero nog iets waar je in je eerste versie geen rekening mee had gehouden, en in de tweede wel.

Als een variabele een array is, en je gebruikt $array, dan wijst $array naar het eerste item in de array.. oftewel. $array = $array[0].

Als je in een recursieve functie $array[0] mee geeft, geef je niet alleen het eerste item mee, maar dus de hele array.

Je tweede oplossing houdt hiero dus ook mooi rekening mee door het gebruik van $value :)

"I had a problem, I solved it with regular expressions. Now I have two problems". That's shows a lack of appreciation for regular expressions: "I know have _star_ problems" --Kevlin Henney