Php 在多维数组中存储元素的完整位置以供重用
这个问题是基于我在这里提出的另一个关于合适的数组处理的问题 在我的例子中,我想展平一个多维数组,但我需要存储该元素的完整密钥,以便以后重用 例如:Php 在多维数组中存储元素的完整位置以供重用,php,arrays,Php,Arrays,这个问题是基于我在这里提出的另一个关于合适的数组处理的问题 在我的例子中,我想展平一个多维数组,但我需要存储该元素的完整密钥,以便以后重用 例如: array( 0 => array( 'label' => 'Item1', 'link' => 'http://google.com', 'children' => null ) 1 => array( 'label' => '
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
)
)
应该扁平化为下表所示的形状
Key Link
===================================
[0] http://google.com
[1] http://google.com
[2] http://google.com
[1][3] http://yahoo.com
问题是,虽然我可以轻松地在多维数组中存储元素的位置,但我发现以后检索该元素非常困难。例如,如果我将密钥存储为
$key=“[1][3]”
,则无法使用$myarray[$key]
访问它。还有其他方法可以做到这一点吗?使用递归的解决方案:
//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.
}
}
使用递归的解决方案:
//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.
}
}
由于数组的深度不是固定的,我想你可以使用(I)
eval
函数——这会吸引大量的-1s(ii)使用recursion@SalmanA:您能否进一步说明如何使用递归?投票结束的人:这个问题的重点是如何从存储的密钥中处理多维数组,而不是如何展平多维数组。可能的重复由于数组的深度不是固定的,我想你可以使用(I)eval
函数——这会吸引很多-1s(ii)使用recursion@SalmanA:您能否进一步说明如何使用递归?投票结束的人:这个问题的重点是如何从存储的密钥中处理多维数组,而不是如何展平多维数组。