phpforeachincrementmodx

Increment in foreach does not increase


MODX version 2.8.4. PHP version 7.3.33.

There is a snippet:

    <?php
    $docId = $modx->getOption('docId', $scriptProperties, '');
    $tmplvarids = array(
         1 => 11
    );
    
    $doitv = array(
            'contentid' => $docId
          , 'tmplvarid' => 17
        );
    $doiget = $modx->getObject('modTemplateVarResource', $doitv);
    $doiextr = $doiget->get('value');
    $doi = str_replace("10.65435/", "", $doiextr);
    
    $i = 0;
    
    foreach($tmplvarids as $tmplvarid) { 
        $suffix = '';
        $artlit = '';
    
        $tvx = $modx->getObject('modTemplateVarResource', array('contentid' => $docId, 'tmplvarid' => $tmplvarid));
        $artlit = $tvx->get('value');
        $prefix = "\n" . '<citation key="key-'. $doi .'-'. $i . '">';
        $str .= str_replace(array('<ul>', '</ul>', '<li>', '</li>'), array('<citation_list>', '</citation_list>', $prefix . '<unstructured_citation>', '</unstructured_citation></citation>'), $artlit);
        $strstrip = strip_tags($str, '<citation><citation_list><unstructured_citation>');
        ++$i; 
    }
    return $strstrip; 
}

Part of the output:

<citation_list>
<citation key="key-2129-8124-2022-3-81-7-12-0">
<unstructured_citation>Aliev BF.</unstructured_citation>
</citation>
<citation key="key-2129-8124-2022-3-81-7-12-0">
<unstructured_citation>Zyzov IM, Gazhva SI.</unstructured_citation>
</citation>
<citation key="key-2129-8124-2022-3-81-7-12-0">
<unstructured_citation>Mamedzade RE.</unstructured_citation>
</citation>
<citation key="key-2129-8124-2022-3-81-7-12-0">
<unstructured_citation>Mitronin AV, Platonova ASh</unstructured_citation>
</citation>
<citation key="key-2129-8124-2022-3-81-7-12-0">
<unstructured_citation>Nasirova HB.</unstructured_citation>
</citation>
</citation_list>

The problem is that there is no number incremention at the end of the construction key-2129-8124-2022-3-81-7-12-0 (must be 1, 2, 3... etc).


Solution

  • Your issue is that you have multiple <li> tags in an $artlit, and so you need to update $i for each one, where at the moment you are only updating $i for the entire <ul>. You can do the update using preg_replace_callback on the <li> tags. Sample code:

    $artlit = str_replace(array('<ul>', '</ul>', '</li>'), array('<citation_list>', '</citation_list>', "</unstructured_citation>\n</citation>"), $artlit);
    $artlit = preg_replace_callback('/<li>/', function ($m) use ($doi, &$i) { return '<citation key="key-'. $doi .'-'. $i++ . '">' . "\n<unstructured_citation>"; }, $artlit);
    $str .= $artlit;
    

    Demo on 3v4l.org

    Note that you should move this line:

    $strstrip = strip_tags($str, '<citation><citation_list><unstructured_citation>');
    

    outside of the foreach as there is no reason to compute it in every iteration. Also note that since $i is incremented in the callback, you no longer need the ++$i in your loop.