[Php-it] Ricercare "figlio" in un array

Cristiano Verondini cverondini at deis.unibo.it
Tue Feb 6 12:52:50 CET 2007


> Lo rimando :-) con qualche commento in più ( non è che mi viene in
> mente una approccio molto più chiaro, dovendo anche creare, vedi
> sotto)

    Io ho trovato questa soluzione. Nota che ho separato le funzioni di 
decodifica del 'path' verso l'elemento e di ricerca all'interno dell'array:

 $var = array(

  'ciao' => array(
   'miao' => array(
    'bao' => 'valore'
   )
  )
 );

 var_dump($var);

  // test per la ricerca

 $el =& FindInArray($var, array('ciao', 'miao', 'bao'));
 $el = 'Nuovo Valore';
 var_dump($var);

  // test per la creazione

 $el =& FindInArray($var, array('uno', 'due', 'tre'), TRUE);
 $el = 'Elemento creato';
 var_dump($var);

  // test per la decodifica del path

 var_dump(PathDecode('root'));
 var_dump(PathDecode('root[l1][l2][l3]'));

  // decodifica un path nella forma:
  // root[l1][l2][l3]
  // restituendo:
  // array('root', 'l1', 'l2', 'l3')

function PathDecode($path) {

 return preg_split('/[^\w]+/', $path, -1, PREG_SPLIT_NO_EMPTY);
}

function &FindInArray(&$var, $path, $create = FALSE){

 $el =& $var;
 for ($i = 0, $m = count($path); $i < $m; $i++) {

  if (! isset($el[ $path[$i] ])) {

   if (! $create)
    return NULL;

   $el[ $path[$i] ] = '';
  }

  $el =& $el[ $path[$i] ];
 }

 return $el;
} 



More information about the Php-it mailing list