Browse recursive array

0

Good, I'm with a problem explained more or less, I need to go through the array and go concatenating father and son, now we need to go concatenated only if you have children ... suppose this is my array:

$rows2 = array(
array(
    'id' => 142,
    'name' => "Cate 1",
    'slug' => "Cate 1",
    'childs' =>

        array(
            'id' => 143,
            'name' => "Cate1 nivel 2",
            'slug' => "Cate1 nivel 2",
            'childs' => array()
        ),
        array( 
            'id' => 144,
            'name' => "Cate1 nivel 3",
            'slug' => "Cate1 nivel 3",
            'childs' => array()
        ),
        array(
            'id' => 145,
            'name' => "Cate1 nivel 4",
            'slug' => "Cate1 nivel 4",
            'childs' => array(
                'id' => 144,
                'name' => "Cate1 nivel 5",
                'slug' => "Cate1 nivel 5",
                'childs' => array()
            )
        )
)),

array(
'id' => 145,
'name' => "Cate 2",
'slug' => "Cate 2",
'childs' => array(
    'id' => 146,
    'name' => "Cate2 nivel 2",
    'slug' => "Cate2 nivel 2",
    'childs' => array()
))
);

If we look, the array of $ rows2 has a father with several children, now, what I try is to concatenate only 1 child with the father, it would be more or less like this:

Cate 1|Cate1 nivel 2
Cate 1|Cate1 nivel 3
Cate 1|Cate1 nivel 4

And in the case of having more than one level that verifies and concatenates me also with that level, example with the array id 145 that I would stay like this:

Cate 1|Cate1 nivel 4|Cate1 nivel nivel 5

That if it has more levels, you should be able to have a condition, I think.

This function I have so far ...

$ant="";

foreach($rows as $row){
    array_walk_recursive($row, 'test_print', ["cadena"=>&$ant]);
    echo "\n";
    $ant="";
}

function test_print($item, $key, $ant){
    if($key == "name"){
        if(empty($ant["cadena"]))
            $ant["cadena"] .= $item;
        else
            $ant["cadena"] .= "|".$item;    
        echo  $ant["cadena"]."\n";      
    }
}
    
asked by 06.02.2018 в 22:02
source

1 answer

0

I understand that you want to paint the "path" of the leaf elements, those that do not have children. I would do it like this:

function escribe_hojas ($item, $ancestors = []) {
    $ancestors[] = $item['name'];

    if ( count($item['childs']) == 0 ) {
        echo implode('|', $ancestors) . "\n";
    } else {
        foreach ($item['childs'] as $child) {
            escribe_hojas($child, $ancestors);
        }
    }
}

foreach ($rows2 as $row) {
    escribe_hojas($row);
}

I have noticed that you have nesting failures in the example array. Specifically, the children of each node (by the way, the plural of child is children , not childs ) must be in an array. I edit the question.

    
answered by 08.02.2018 / 23:18
source