PHP数组树阵 [英] PHP array to tree array
本文介绍了PHP数组树阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个问题,我无法修复。我有2个数组和字符串。第一个数组包含第二个应该使用的键。第一个是这样的:
I have a problem I cannot fix. I have 2 arrays and a string. The first array contains the keys the second one should use. The first one is like this:
Array
(
[0] => foo
[1] => bar
[2] => hello
)
现在我需要一个PHP code,它转换为第二个数组:
Now I need a PHP code that converts it to the second array:
Array
(
[foo] => Array
(
[bar] => Array
(
[hello] => MyString
)
)
)
项的数目是可变的。
The number of items is variable.
有人可以告诉我如何做到这一点?
Can someone please tell me how to do this?
推荐答案
您应该使用引用来解决这个问题:
You should use references to solve this problem:
$a = array (0 => 'foo', 1 => 'bar', 2 => 'hello' );
$b = array();
$ptr = &$b;
foreach ($a as $val) {
$ptr[$val] = Array();
$ptr = &$ptr[$val];
}
$ptr = 'MyString';
var_dump($b);
这篇关于PHP数组树阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文