0

I have the following structure and I dont know how to map it(i dont know if "map" is really what i need also :S)

var -> child1 -> subchild1
              -> subchild2 -> subsubchild1

    -> child2 -> subchild3

so, I need to map/parse it to something like this:

     var.child1.subchild1
     var.child1.subchild2.subsubchild1
     var.child2.subchild1

I manage to do it up to the 2nd level:

     var.child1.subchild1
     var.child1.subchild2

This is the code

function foo($a,$txt) {
    if (isset($a['childs'])) {
        foreach ($a['childs'] as $ch) {
            $txt .= foo($ch,$txt);
        }
    } else {
        $txt .= ".".$a['name'];
    }
    return $txt;
}

foreach ($arr as $childs) {
    $aux = $r;
    var_dump(foo($childs,$aux));
    echo "<br>";
}

Do you have any ideas?

Thanks!

1 Answer 1

2

I cannot even imagine why do you need this, but you should use recursion, like this:

<?php
$test_arr = array('name'=>'var','childs'=>
    array(
        array(
            'name'=>'child1',
            'childs'=>array(
                'subchild1',
                array(
                    'name' => 'subchild2',
                    'childs' => array(
                        'subsubchild1',
                        'subsubchild2'
                    )
                )
            )
        ),
        array(
            'name'=>'child2',
            'childs'=> array('subchild1')
        )
    )
);

function map($arr) {
    if(is_array($arr) && isset($arr['childs']) && $arr['childs']) {
        $result = array();
        foreach($arr['childs'] as $child) {
            foreach(map($child) as $child2) $result[] = $arr['name'].".".$child2;
        }
        return $result;
    }
    else return array($arr);
}

print_r(map($test_arr));
?>

Gives:

Array
(
    [0] => var.child1.subchild1
    [1] => var.child1.subchild2.subsubchild1
    [2] => var.child1.subchild2.subsubchild2
    [3] => var.child2.subchild1
)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I had to make some changes but it worked. it is for a mongodb query, to check if the field exist: find('var.child1.subchild1':{'$exists':true});

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.