Re: Dynamically creating multi-array field

From: Date: Mon, 27 Oct 2008 06:09:27 +0000
Subject: Re: Dynamically creating multi-array field
References: 1 2 3 4 5 6  Groups: php.general 
Request: Send a blank email to php-general+get-282469@lists.php.net to get a copy of this message
On Sun, 2008-10-26 at 22:39 -0700, Jim Lucas wrote: > > Even slimmer > > <?php > > $node = '[5][1][]'; > $text = 'some text'; > > preg_match_all('|\[([^\]\[]*)\]|', $node, $matches, > PREG_PATTERN_ORDER); > > $recursive = $matches[1]; > > $recursive = array_reverse($recursive); > > foreach ( $recursive AS $index ) { > > $out = array(); > > $out[(int)$index] = $text; > > $text = $out; > > } > > print_r($out); > ?> It's buggy... you need to test for an blank string to properly handle the append to array case when the index is blank []. <?php $node = '[5][1][]'; $text = 'some text'; preg_match_all( '|\[([^\]\[]*)\]|', $node, $matches, PREG_PATTERN_ORDER ); $recursive = $matches[1]; $recursive = array_reverse($recursive); foreach( $recursive AS $index ) { $out = array(); if( trim( $index ) === '' ) { $out[] = $text; } else { $out[$index] = $text; } $text = $out; } print_r( $out ); ?> I also removed the (int) cast since integer keys will be cast automatically by PHP and then it will have support for text keys also. Cheers, Rob. -- http://www.interjinn.com Application and Templating Framework for PHP

« previous php.general (#282469) next »