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

Asked

Viewed 185 times

0

I’m trying to make a breadcrumb dynamic and need to make a loop to mount the link. At 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>

What little I got was using unset to generate a new array. After this for to mount the repetition, i still need 2 more loops and reverse the order. A hell of a gambiarra.

foreach( $list as $i => $item ){
    $newlist[] = $list;
    unset( $list[$i] );
}
  • 1

    Just one question: does the breadcrumb label really need to occupy another position in your array? Wouldn’t it be better to be an associative array? Ex.: array('item' => 'Label', 'bairro' => 'Bairro', 'rua' => 'Rua')

  • @Thomas, It would be better yes, but as I said, it is dynamic and with several sub items. If I could redo the array I would have no problem.

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>';
}

Exit:

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

1

I will leave another possibility, more complex and less performative than Márcio’s, but still valid.

If you transpose the original matrix will always have an array of two indices, one with the Labels and the other with the Breadcrumbs.

Combine the indexes into a new matrix (described here as $Breadcrumbs) and eternal:

$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 );
}
  • Thanks Bruno, the problem is the array order. I found it more practical to work in pairs..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.