Loop to repeat previous keys (3, 32, 321, ...)

0

I'm trying to make a breadcrumb dynamic and need to loop to mount the link. For each loop, it needs to repeat the previous items, as in the example below the array and the output.

array( array( 'Bairro' , 'bairro' ) , array( 'Rua' , 'rua' ) )

<a href="bairro">Bairro</a>
<a href="bairro/rua">Rua</a>

The little I got was using unset to generate a new array. After that for to mount the repetition , I still need 2 more loops and revert the order. A little gambiarra.

foreach( $list as $i => $item ){
    $newlist[] = $list;
    unset( $list[$i] );
}
    
asked by anonymous 23.11.2014 / 10:07

2 answers

3

I believe that by accumulating the link in a variable you get the result you expect, for example:

$breadcrumbs = array( array( 'Bairro' , 'bairro' ) , array( 'Rua' , 'rua' ) );

foreach ( $breadcrumbs as $item ) {
    $link_acumulado .= $item[1] . '/';

    echo '<a href="' . trim( $link_acumulado, '/' ) . '">' . $item[0] . '</a>';
}

Output:

<a href="bairro">Bairro</a>
<a href="bairro/rua">Rua</a>
    
23.11.2014 / 17:49
1

I'll leave another possibility, more complex and less performative than that of Márcio, but still valid.

If you transpose the original array will always have an array of two indexes, one with the labels and another one with the breadcrumbs .

Combine the indexes in a new array (here described as $ breadcrumbs ) and iterate:

$previous = NULL;

$last = key( array_slice( $breadcrumbs, -1, 1, TRUE ) );
$separator = ' &raquo; ';

foreach( $breadcrumbs as $label => $breadcrumb ) {

    $previous .= sprintf( '/%s', $breadcrumb );

    if( $label == $last ) $separator = NULL;

    printf( '<a href="%s">%s</a>%s', $previous, $label, $separator );
}
    
23.11.2014 / 19:00