鉴于我有一个数组:
$array = array(
'a' => array(
'b' => array(
'c' => 'hello',
),
),
'd' => array(
'e' => array(
'f' => 'world',
),
),
);
我希望将其“展平”为单个维度的引用查找,将键与分隔符连接(在本示例的情况下为,正斜杠/
)< / p>
在成功输出上执行var_dump()
会产生:(记下所有引用)
array(6) {
["a"]=>
&array(1) {
["b"]=>
&array(1) {
["c"]=>
&string(5) "hello"
}
}
["a/b"]=>
&array(1) {
["c"]=>
&string(5) "hello"
}
["a/b/c"]=>
&string(5) "hello"
["d"]=>
&array(1) {
["e"]=>
&array(1) {
["f"]=>
&string(5) "world"
}
}
["d/e"]=>
&array(1) {
["f"]=>
&string(5) "world"
}
["d/e/f"]=>
&string(5) "world"
}
array(2) {
["a"]=>
&array(1) {
["b"]=>
&array(1) {
["c"]=>
&string(5) "hello"
}
}
["d"]=>
&array(1) {
["e"]=>
&array(1) {
["f"]=>
&string(5) "world"
}
}
}
目前,我正在使用它:
function build_lookup(&$array, $keys = array()){
$lookup = array();
foreach($array as $key => &$value){
$path = array_merge($keys, (Array) $key);
$lookup[implode('/', $path)] = &$value;
if(is_array($value)){
$lookup = array_merge($lookup, build_lookup($value, $path));
}
}
return $lookup;
}
但是,我试图通过删除递归元素来改进它(切换到堆栈/弹出方法)这样做的问题是参考保留,因为典型的递归到 - 非递归方法:
$stack = $input;
while(!empty($stack)){
$current = array_pop($stack);
// do stuff and push to stack;
}
...因参考而失败。
我在SO上看到了一些类似的问题/答案,但其中没有一个处理引用(因为它不是提问者的意图)
这里有更好的(读取更快的)方法吗?
最终解决方案(感谢@chris ):
/**
*
* @return array
*/
public function get_lookup_array()
{
$stack = $lookup = array();
try
{
foreach($this->_array as $key => &$value)
{
$stack[$key] = &$value;
}
while(!empty($stack))
{
$path = key($stack);
$lookup[$path] = &$stack[$path];
if(is_array($lookup[$path]))
{
foreach($lookup[$path] as $key => &$value)
{
$stack[$path . $this->_separator . $key] = &$value;
}
}
unset($stack[$path]);
}
}
catch(\Exception $exception)
{
return false;
}
return $lookup;
}
答案 0 :(得分:2)
header('content-type:text/plain');
$arr = array(
'a' => array(
'b' => array(
'c' => 'hello',
),
),
'd' => array(
'e' => array(
'f' => 'world',
),
),
);
//prime the stack using our format
$stack = array();
foreach ($arr as $k => &$v) {
$stack[] = array(
'keyPath' => array($k),
'node' => &$v
);
}
$lookup = array();
while ($stack) {
$frame = array_pop($stack);
$lookup[join('/', $frame['keyPath'])] = &$frame['node'];
if (is_array($frame['node'])) {
foreach ($frame['node'] as $key => &$node) {
$keyPath = array_merge($frame['keyPath'], array($key));
$stack[] = array(
'keyPath' => $keyPath,
'node' => &$node
);
$lookup[join('/', $keyPath)] = &$node;
}
}
}
var_dump($lookup);
// check functionality
$lookup['a'] = 0;
$lookup['d/e/f'] = 1;
var_dump($arr);
或者你可以做这样的事情来获得引用/ w array_pop功能
end($stack);
$k = key($stack);
$v = &$stack[$k];
unset($stack[$k]);
这是有效的,因为php数组具有按键创建时间排序的元素。 unset()删除密钥,从而重置该密钥的创建时间。