0

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!

2 Answers 2

2
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) } 
Sign up to request clarification or add additional context in comments.

1 Comment

You made this really difficult because you mixed numeric and associative arrays and you didn't want the numeric values real parents but instead you wanted their grandparents.
0

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

1 Comment

He didn't request it as html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.