本文介绍了PHP - 转换多维数组到二维数组点符号键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有很多的技巧和code的例子在那里访问PHP阵列,点符号,但我想这样做有点相反。我想借一个多维数组是这样的:
$ myArray的=阵列(
'键1'=> VALUE1,
'键2'=>阵列(
'子'=> subkeyval
)
KEY3'=> 值3,
KEY4'=>阵列(
subkey4'=>阵列(
subsubkey4'=> subsubkeyval4',
subsubkey5'=> subsubkeyval5',
)
subkey5'=> subkeyval5
)
);
和把它变成这个(可能通过一些递归函数):
$ newArray =阵列(
'键1'=> VALUE1,
key2.subkey'=> subkeyval',
KEY3'=> 值3,
key4.subkey4.subsubkey4'=> subsubkeyval4',
key4.subkey5.subsubkey5'=> subsubkeyval5',
key4.subkey5'=> subkeyval5
);
解决方案
德codeZ
$ ritit =新RecursiveIteratorIterator(新RecursiveArrayIterator($ myArray的));
$结果=阵列();
的foreach($ ritit为$ leafValue){
$键=阵列();
的foreach(范围(0,$ ritit-> getDepth()),为$深度){
$键[] = $ ritit-> getSubIterator($深度) - GT;键();
}
$结果[加入(,$钥匙'。')] = $ leafValue;
}
输出
阵列
(
[键1] =>值1
[key2.subkey] => subkeyval
[KEY3] => VALUE3
[key4.subkey4.subsubkey4] => subsubkeyval4
[key4.subkey4.subsubkey5] => subsubkeyval5
[key4.subkey5] => subkeyval5
)
演示:
我需要去,但如果需要,明天的说明,问我。
There are plenty of tips and code examples out there of accessing PHP arrays with dot notation, but I would like to do somewhat the opposite. I would like to take a multidimensional array like this:
$myArray = array(
'key1' => 'value1',
'key2' => array(
'subkey' => 'subkeyval'
),
'key3' => 'value3',
'key4' => array(
'subkey4' => array(
'subsubkey4' => 'subsubkeyval4',
'subsubkey5' => 'subsubkeyval5',
),
'subkey5' => 'subkeyval5'
)
);
And turn it into this (likely through some recursive function):
$newArray = array(
'key1' => 'value1',
'key2.subkey' => 'subkeyval',
'key3' => 'value3',
'key4.subkey4.subsubkey4' => 'subsubkeyval4',
'key4.subkey5.subsubkey5' => 'subsubkeyval5',
'key4.subkey5' => 'subkeyval5'
);
解决方案
teh codez
$ritit = new RecursiveIteratorIterator(new RecursiveArrayIterator($myArray));
$result = array();
foreach ($ritit as $leafValue) {
$keys = array();
foreach (range(0, $ritit->getDepth()) as $depth) {
$keys[] = $ritit->getSubIterator($depth)->key();
}
$result[ join('.', $keys) ] = $leafValue;
}
output
Array
(
[key1] => value1
[key2.subkey] => subkeyval
[key3] => value3
[key4.subkey4.subsubkey4] => subsubkeyval4
[key4.subkey4.subsubkey5] => subsubkeyval5
[key4.subkey5] => subkeyval5
)
demo: http://codepad.org/YiygqxTM
I need to go, but if you need an explanation of that tomorrow, ask me.
这篇关于PHP - 转换多维数组到二维数组点符号键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!