tags:

views:

101

answers:

3

Say I have a form with these fields, and cannot rename them:

<input type="text" name="foo[bar]" />
<input type="text" name="foo[baz]" />
<input type="text" name="foo[bat][faz]" />

When submitted, PHP turns this into an array:

Array
(
    [foo] => Array
        (
            [bar] => foo bar
            [baz] => foo baz
            [bat] => Array
                (
                    [faz] => foo bat faz
                )

        )

)

What methods are there to convert or flatten this array into a data structure such as:

Array
(
    [foo[bar]] => foo bar
    [foo[baz]] => foo baz
    [foo[bat][faz]] => foo bat faz
)
A: 

May be stupid answer but why not to make it

<input type="text" name="foobar" />
<input type="text" name="foobaz" />
<input type="text" name="foobatfaz" />

?

Col. Shrapnel
First sentence of the question: "Say I have a form with these fields, and cannot rename them..."
Frank Farmer
A: 

Not the answer to your question but alternatively there is extract which will take an array and produce variables from them. eg;

$array = array
    (
        [foo] => foo bar
        [boo] => something else
    )
extract($array);

Output

$foo = 'foo bar';
$boo = 'something else';

There are a few options on how to handle identically index names for example, over write existing value or append a prefix to the variable name.

bigstylee
using `extract` with user input is always bad idea
Col. Shrapnel
a very valid point. had not considerred this.
bigstylee
+3  A: 

I think this is what you want

$ritit = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
$result = array();
foreach ($ritit as $leafValue) {
    $path = 'foo99';
    foreach (range(0, $ritit->getDepth()) as $depth) {
        $path .= sprintf('[%s]', $ritit->getSubIterator($depth)->key());
    }
    $result[$path] = $leafValue;
}

By default, RecursiveIteratorIterator only visits leaf nodes, so each iteration of the outer foreach loop has the iterator structure stopped on one of the values you care about. We find the keys that build our path to where we are by taking a peek at the iterators that RecursiveIteratorIterator is creating and managing for us(one iterator is used for each level).

chris
Awesome, thanks chris! I should really learn more about the SPL
deadkarma