拼合一个PHP数组 [英] Flatten a PHP array
问题描述
说我有这些领域的一种形式,而不能重命名它们:
<输入类型=TEXTNAME =foo的[酒吧]/>
<输入类型=文本名称=福[巴兹]/>
<输入类型=文本名称=福[蝙蝠] [FAZ]/>
在提交时,PHP变成一个数组这样的:
阵列
(
[富] =>排列
(
[巴] =>富巴
[巴兹] =>富巴兹
[蝙蝠] =>排列
(
[FAZ] =>富蝙蝠FAZ
) ))
什么方法有转换或拼合此数组的数据结构,如:
阵列
(
[富[巴] =>富巴
[富[巴兹] =>富巴兹
[富[蝙蝠] [FAZ] =>富蝙蝠FAZ
)
我想这是你想要的。
$ ritit =新RecursiveIteratorIterator(新RecursiveArrayIterator($ ARR));
$结果=阵列();
的foreach($ ritit为$ leafValue){
$ PATH ='foo99';
的foreach(范围(0,$ ritit-> getDepth()),为$深度){
。$ PATH = sprintf的('[%S]',$ ritit-> getSubIterator($深度) - GT;键());
}
$结果[$ PATH = $ leafValue;
}
在默认情况下,只有RecursiveIteratorIterator访问叶节点,所以外层的foreach循环的每次迭代具有迭代结构停在你关心的一个值。我们发现,建于我们通过采取偷看了RecursiveIteratorIterator创造,为我们管理(一个迭代器被用于每个级别)的迭代器,其中我们的道路的关键。
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
)
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).
这篇关于拼合一个PHP数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!