2

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
)
deadkarma
  • 3,144
  • 2
  • 17
  • 19
  • 1
    Come on it's not that hard to search! Here's some bing results: http://www.bing.com/search?q=php%2Barray%2Bflatten And here's one from stack overflow: http://stackoverflow.com/questions/1319903/how-to-flatten-a-multidimensional-array – encee Apr 23 '10 at 22:41
  • 1
    A typical array flatten is not what's being asked for. All the keys in every path to every leaf node is the question, and then build a string out of the keys in each path. – goat Apr 24 '10 at 03:18

3 Answers3

4

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).

goat
  • 31,486
  • 7
  • 73
  • 96
0

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" />

?

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
-2

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
  • 1,240
  • 1
  • 12
  • 22