开发者

Flatten a PHP array

开发者 https://www.devze.com 2022-12-27 19:39 出处:网络
Say I have a form with these fields, and cannot rename them: <input type=\"text\" name=\"foo[bar]\" />

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 fla开发者_运维知识库tten this array into a data structure such as:

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


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


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

?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号