将元素的完整位置存储在多维数组中以供重用
This question is based on my other question here about a suitable array processing algorithm.
In my case, I want to flatten a multidimensional array, but I need to store the full key to that element for reuse later.
For example :
array(
0 => array(
'label' => 'Item1',
'link' => 'http://google.com',
'children' => null
)
1 => array(
'label' => 'Item2',
'link' => 'http://google.com',
'children' => array( 3 => array(
'label' => 'SubmenuItem1',
'link' => 'http://www.yahoo.com',
'children' => null
)
)
)
2 => array(
'label' => 'Item3',
'link' => 'http://google.com',
'children' => null
)
)
Should be flattened into something like the following table
Key Link
===================================
[0] http://google.com
[1] http://google.com
[2] http://google.com
[1][3] http://yahoo.com
The problem is that I while I can easily store the location of an element in a multidimensional array, I am finding it to be quite hard to retrieve that element later. For example, if I store my key as $key = "[1][3]"
, I can not access it using $myarray[$key]
. Is there anyway to do this?
这个问题基于我在这里关于合适的数组处理的另一个问题算法。 p>
在我的例子中,我想要展平多维数组,但是我需要将完整的密钥存储到该元素中以便以后重用。 p>
例如: p>
array(
0 => array(
'label'=>'Item1',
'link'=>'http:// google .com',
'children'=> null
)
1 => array(
'label'=>'Item2',
'link'=>'http:/ /google.com',
'children'=>数组(3 =>数组(
'标签'=>'SubmenuItem1',
'链接'=>'http://www.yahoo .com',
'children'=> null
)
)
)
2 =&g 吨; 数组(
'标签'=>'第3项',
'链接'=>'http://google.com',
'儿童'=> null
)
)
pre>
应该扁平化为类似下表的内容 p>
Key Link
========= ==========================
[0] http://google.com
[1] http://google.com
[2] http://google.com
[1] [3] http://yahoo.com
code> pre>
问题在于我 我可以轻松地将元素的位置存储在多维数组中,我发现稍后检索该元素非常困难。 例如,如果我将我的密钥存储为 $ key =“[1] [3]” code>,我无法使用 $ myarray [$ key] code>访问它。 反正有吗? p>
div>
Solution using recursion:
//Array parts should be an array containing the keys, for example, to address
//SubmenuItem1, I had 1.3 when the array was flattened. This was then exploded() to the array [1, 3]
$this->recurseIntoArray($myArray, $arrayParts);
private function recurseIntoArray(&$array, $arrayParts){
$current = $arrayParts[0];
$array[$current]['blah'] = 'blah'; //If you want to update everyone in the chain on the way down, do it here
array_shift($arrayParts);
if (!empty($arrayParts)){
$this->recurseIntoArray($array[$current]['children'], $arrayParts);
}else{
//If you want to update only the last one in the chain, do it here.
}
}