如果不清楚的话请耐心等待;我无法完全绕过这个(因此我在这里寻求帮助)。
我有一个如下所示的数组:
Array
(
[DimA1] => Array
(
[DimB1] => Array
(
[DimC1] => Array
(
[value1] => 13708
[value2] => 4.5
)
[DimC2] => Array
(
[value1] => 1846
[value2] => 15.8
)
)
[DimB2] => Array
(
[DimC1] => Array
(
[value1] => 18166
[value2] => 6.4
)
)
[DimA2] => Array
(
....... etc
我需要逐步完成这个数组,当我得到value1和value2时,我需要做一些数据库插入。此时,我需要知道我目前正在执行哪些数组,并将其键名作为数据库插入的一部分。
我目前的解决方案如下:
public function recurseCounts($array,$dims = array()) {
foreach ($array as $key => $value) {
$dims[] = $key;
if (isset($value['value1']) || isset($value['value2'])) {
print_r($value); // For debugging...
print_r($dims); // For debugging...
// DB Logic to insert dimensions in to DB here
// DB Logic to insert values in to DB here
array_pop($dims);
} else {
$this->recurseCounts($value,$dims);
}
}
}
直到循环达到DimB2为止,这就是事情开始变得糟糕的地方。
关于如何解决这个问题的任何想法?
答案 0 :(得分:2)
你总是加入$ dims。
$ dims现在会:
DimA1
DimA1, DimB1
DimA1, DimB1, DimC1
DimA1, DimB1, DimC2
DimA1, DimB1, DimB2
DimA1, DimB1, DimB2, DimC1
DimA1, DimB1, DimB2, DimC2
如果你将array_pop移到外面,你应该没问题。
public function recurseCounts($array,$dims = array()) {
foreach ($array as $key => $value) {
$dims[] = $key;
if (isset($value['value1']) || isset($value['value2'])) {
print_r($value); // For debugging...
print_r($dims); // For debugging...
// DB Logic to insert dimensions in to DB here
// DB Logic to insert values in to DB here
} else {
$this->recurseCounts($value,$dims);
}
array_pop($dims);
}
}
答案 1 :(得分:1)
您需要跟踪元素的完整路径,因为深度“C”处的键是相同的:
public function recurseCounts($array,$dims = array(),$path = '') {
foreach ($array as $key => $value) {
$dims[] = ($path ? $Path.'_' : '').$key; // Add the full path (separated by '_')
if (isset($value['value1']) || isset($value['value2'])) {
print_r($value); // For debugging...
print_r($dims); // For debugging...
// DB Logic to insert dimensions in to DB here
// DB Logic to insert values in to DB here
array_pop($dims);
} else {
$this->recurseCounts($value,$dims,end($depth)); // pass it on
}
}
}