Reputation: 67
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.
Thanks very much for any help!
Upvotes: 0
Views: 234
Reputation: 995
You could do this with an recursive function, that has the "parent" as optional second parameter.
$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
Upvotes: 0
Reputation: 1969
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) }
Upvotes: 2