Re: Dynamically creating multi-array field

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux