Variable accumulates data in a foreach - PHP

0

I have a foreach that runs through an array to show me some links of the images. When I create more than one block, the images of this one and those of the first block are shown in the 2nd.

if ( isset( $block['images'] ) ){

  foreach(array_column($block['images'], 'image') as $idImagen) {
    $url[] = brc_make_link_relative_if_local( wp_get_attachment_url( $idImagen ) );
  }

  $data_array[$section_key][$section_data_key][$block_key]['images'] = $url;
}   

And as you can see, the links are repeated. I guess it should not be something difficult, but rather some method of cleaning the variable that I'm returning or something like that.

As you can see in images of the second block they are repeating

    
asked by Santiago D'Antuoni 12.12.2016 в 17:59
source

1 answer

2

The problem is that $url is storing all the elements that are processed in the foreach ... however once you have dumped the elements you do not reset the array, so in successive passes you will have more and more elements.

You should restart the variable before every foreach :

if ( isset( $block['images'] ) ){

  unset($url);
  $url= array();

  foreach(array_column($block['images'], 'image') as $idImagen) {
    $url[] = brc_make_link_relative_if_local( wp_get_attachment_url( $idImagen ) );
  }

  $data_array[$section_key][$section_data_key][$block_key]['images'] = $url;
}
    
answered by 12.12.2016 / 18:03
source