P
P
pavelmosin2019-12-13 12:04:36
1C-Bitrix
pavelmosin, 2019-12-13 12:04:36

CIBlockSection::Add in a loop?

How to add all sections from an array? After the loop is completed, the last of the $arSectionToAdd sections is added

<?
  $arSectionToAdd = array (
    'sect-1',
    'sect-2',
    'sect-3',
    'sect-4',
  );


  $bs = new CIBlockSection;


  foreach (  $arSectionToAdd as $sectionToAddd  ) {


    $codeSection = str_replace(
      '.',
      '-',
      $sectionToAddd
    );


    $arFields = Array(
      "ACTIVE" => 'Y',
      "IBLOCK_SECTION_ID" => false,
      "IBLOCK_ID" => 43,
      "NAME" => $sectionToAddd,
      "CODE" => $codeSection,
      "SORT" => '500',
      "PICTURE" => '',
      "DESCRIPTION" => '',
      "DESCRIPTION_TYPE" => ''
    );


    if( $ID > 0 ) {

      $res = $bs->Update(
        $ID,
        $arFields
      );
    }	else {

      $ID = $bs->Add($arFields);
      $res = ( $ID > 0 );
    }
  }
?>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Gritsuk, 2019-12-13
@pavelmosin

Your code is written so that the first element is added and all subsequent elements are updated. This happens because of the if( $ID > 0 ) condition.
$ID = $bs->Add($arFields);//add an element and write its ID to the variable
$res = ( $ID > 0 );
And at the next step, without resetting the ID variable, the previous record is updated.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question