[英]Return all node values with their parents in PHP multidimensional array
I have a simple multidimensional array like this: ` 我有一个简单的多维数组,如下所示:
$array= [
'A' => [
'B' => ['D', 'E', 'F'],
'C' => 'G',
],
];
I need to return all node values with their parents. 我需要与父母一起返回所有节点值。 So I need an output like:
所以我需要这样的输出:
P[A] = 0;
P[B] = A;
P[D] = B;
P[E] = B;
P[F] = B;
P[C] = A;
P[G] = C;
I've tried some functions like array_search()
, array_walk_recursive
and so on, but I couldn't apply these functions to my situation. 我已经尝试了一些函数,例如
array_search()
, array_walk_recursive
等,但是我无法将这些函数应用于我的情况。 Thanks very much for any help! 非常感谢您的帮助!
function recursive($arr, $parentKey, &$flattened) {
foreach ($arr as $key => $item) {
if (is_array($item)) {
recursive($item, $key, $flattened);
$flattened[$key] = $parentKey;
} else {
if (is_numeric($key)) {
$flattened[$item] = $parentKey;
} else {
$flattened[$item] = $key;
$flattened[$key] = $parentKey;
}
}
}
}
$inputArray= [
'A' => [
'B' => ['D', 'E', 'F'],
'C' => 'G'
]
];
$result = [];
recursive($inputArray, 0, $result);
var_dump($result); // array(7) { ["D"]=> string(1) "B" ["E"]=> string(1) "B" ["F"]=> string(1) "B" ["B"]=> string(1) "A" ["G"]=> string(1) "C" ["C"]=> string(1) "A" ["A"]=> int(0) }
You could do this with an recursive function, that has the "parent" as optional second parameter. 您可以使用递归函数来完成此操作,该函数具有“ parent”作为可选的第二个参数。
$array = [
'A' => [
'B' => [ 'D', 'E', 'F' ],
'C' => 'G',
],
];
function showParents($arr, $parent = 0) {
foreach($arr as $key => $val) {
if(is_array($val)) {
// for when the element is an array
echo '[' . $key . '] ' . $parent . '<br>';
} else if(is_int($key)){
// for when the array is an not-associative one (or are you using INTs as keys also?)
echo '[' . $val . '] ' . $parent . '<br>';
} else if(is_string($val)){
// for when the value is a string ('C' => 'G')
echo '[' . $key . '] ' . $parent . '<br>';// display parent of C
echo '[' . $val . '] ' . $key . '<br>';// display parent of G
}
if(is_array($val)) {
// when the current value is an array, go deeper
showParents($val, $key);
}
}
}
showParents($array);
Displays: 显示:
[A] 0
[B] A
[D] B
[E] B
[F] B
[C] A
[G] C
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.